Search code examples
audionaudio

NAudio - Does a new instance of OffsetSampleProvider have to be created for each playback


As explained here, OffsetSampleProvider can be used in order to play a specific portion of an audio file. Like this:

AudioFileReader AudioReader = new AudioFileReader("x.wav");
OffsetSampleProvider OffsetProvider = New OffsetSampleProvider(AudioReader);

OffsetProvider.SkipOver = TimeSpan.FromSeconds(5);
OffsetProvider.Take = TimeSpan.FromSeconds(8);

myWaveOut.Init(OffsetProvider);
myWaveOut.Play();

The above example will play an audio for 8 seconds, starting at second 5. However, if I want to play it again, it will not play, unless I set the Position property of the AudioFileReader to 0, and re-create a new instance of OffsetSampleProvider from it. So I would like to know if I'm missing something, or this is the way that OffsetSampleProvider should be used (and if it does, do I have to free any resources related to it).


Solution

  • You could copy the code for OffsetSampleProvider and add a Reset method to it. I'd also avoid using SkipOver for performance reasons and just set the CurrentTime of the AudioFileReader to 5 seconds directly before you play.