Thursday 13 September 2012

NAudio OffsetSampleProvider

I’ve added a new class to NAudio ready for the 1.6 release called the OffsetSampleProvider, which is another utility class implementing the ISampleProvider interface.

It simply passes through audio from a source ISampleProvider, but with the following options:

  1. You can delay the start of the source stream by using the DelayBySamples property. So if you want to insert a few seconds of silence, you can use this property.
  2. You can discard a certain number of samples from your source using the SkipOverSamples property
  3. You can limit the number of samples you read from the source using the TakeSamples property. If this is 0, it means take the whole thing. If it is any other value, it will only pass through the specified number of samples from the source.
  4. You can also add a period of silence to the end by using the LeadOutSamples property.

You can convert a TimeSpan to a number of samples using the following logic (Remember to multiply by channels). I may add a helper method to OffsetSampleProvider that can do this for you in future.

int sampleRate = offsetSampleProvider.WaveFormat.SampleRate;
int channels = offsetSampleProvider.WaveFormat.Channels;
TimeSpan delay = TimeSpan.FromSeconds(1.7); // set to whatever you like
int samplesToDelay = (int)(sampleRate * delay.TotalSeconds) * channels;
offsetSampleProvider.DelayBySamples = samplesToDelay;

It’s a fairly simple class, but it is quite powerful. You might use it for inputs to a mixer, where you want to delay each input by a certain amount to align the audio properly. Or you might use it to cut a piece out of a longer section of audio.

Note that the skipping over is implemented by reading from the source because ISampleProvider does not support repositioning. So if your source is (say) an AudioFileReader, it would perhaps be better to use the Position property to get to the right place before handing it to OffsetSampleReader.

No comments: