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();


Of course you could equally use WaveFileWriter to write the extract to a WAV file if you wanted to save it for playback later.

Want to get up to speed with the the fundamentals principles of digital audio and how to got about writing audio applications with NAudio? Be sure to check out my Pluralsight courses, Digital Audio Fundamentals, and Audio Programming with NAudio.
Vote on HN
comments powered by Disqus