简体   繁体   English

如何在 C# 中播放声音文件的一部分?

[英]How to play a portion of a sound file in C#?

I want to play any specific portion of a sound file in C#.我想在 C# 中播放声音文件的任何特定部分。 for example: an audio file is of 10 seconds.例如:一个音频文件是 10 秒。 I want play the sounds that is only within 5 seconds to 8 seconds duration.我想播放只有 5 秒到 8 秒持续时间的声音。

so, only a specific part that has a start and end position is the sound file will be played nothing else.因此,只有具有开始和结束位置的特定部分是声音文件,不会播放其他任何内容。

I haven't found any support in C#.我还没有在 C# 中找到任何支持。 can any other API help?任何其他 API 可以提供帮助吗?

If you are using .NET 3.0 or later, I do recommend working with MediaPlayer it's a simple class.如果您使用 .NET 3.0 或更高版本,我建议您使用MediaPlayer它是一个简单的类。 Please refer to its documentation on MSDN请参考MSDN上的文档

Here's how you could do it with NAudio ( available on NuGet ):以下是您如何使用NAudio可在 NuGet 上获得)执行此操作的方法:

var file = new AudioFileReader("test.mp3");
// skip the first 15 seconds
file.CurrentTime = TimeSpan.FromSeconds(15);
var trimmed = new OffsetSampleProvider(file);
// only play 10 seconds
var takeDuration = TimeSpan.FromSeconds(10);
trimmed.TakeSamples = (int)(trimmed.WaveFormat.SampleRate * takeDuration.TotalSeconds) * trimmed.WaveFormat.Channels;
var player = new WaveOut();
player.Init(new SampleToWaveProvider16(trimmed));
player.Play();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM