How to play a specific portion of an audio file with NAudio
Occasionally I get asked how to play an extract from an audio file with NAudio. There’s actually a class in NAudio that makes this very simple – OffsetSampleProvider
.
OffsetSampleProvider
allows you to skip over a specified duration from the start of the source audio (with a Skip
property), and to only play a specified duration by using the Take
property. So you could skip the first 30 seconds and then take then next 10 seconds for example. (OffsetSampleProvider
can actually do a bit more than this – it can also insert silence at the start and end)
But just to show how simple it is to use, here’s a code snippet that takes a 10 second extract from an MP3 file, after skipping the first 15 seconds:
var file = new AudioFileReader("somefile.mp3");
var trimmed = new OffsetSampleProvider(file);
trimmed.SkipOver = TimeSpan.FromSeconds(15);
trimmed.Take = TimeSpan.FromSeconds(10);
var player = new WaveOutEvent();
player.Init(trimmed);
player.Play();
Of course you could equally use WaveFileWriter
to write the extract to a WAV file if you wanted to save it for playback later.