Search code examples
bufferplaybacknaudio

Periodically refill BufferedWaveProvider with NAudio (C#)


I read audio data from a wave file and save this audio data (without the wave header information) in a byte[]. Now I want to use NAudio in my C# project to stream from this byte[]. I would like the buffer to be ~100ms long and to periodically refill it, so the playback never stops.

I can create my BufferedWaveProvider object and fill it with the first x bytes from my byte[] but: How can I find out when the buffer is running low?

Let's say I have the buffer filled for the first time. When I start playback via my WavePlayer object, the playback stops after the buffer was played back. But how do I refill this buffer with the next chunk of audio data before the playback cursor reaches the end of the buffer?

Reason behind this is: I want to convert each buffer data via FFT so I can plot the current frequencies in my GUI.

I hope somebody can help me out here.


Solution

  • Why use a BufferedWaveProvider at all for this scenario? Just pass your WaveFileReader / AudioFileReader through a SampleAggregator (see the example in the source code for the NAudio WPF Demo) and then play from that. You can then have an event raised every time an FFT is calculated, and it means that the soundcard read size doesn't have to match the size of the FFT (which is usually won't as it won't necessarily read a power of two sampele)