naudioplayback

NAudio PlaybackState always Playing


I have this bit of code in a .NET console application to play a recorded sound-check using NAudio:

    static void Play(int outputDeviceIndex, byte[][] recordedChunks)
    {
        using (var waveOut = new WaveOutEvent())
        {
            waveOut.DeviceNumber = outputDeviceIndex;
            waveOut.PlaybackStopped += (sender, args) => Console.WriteLine("Playback stopped: " + args.Exception);

            var bufferedWaveProvider = new BufferedWaveProvider(new WaveFormat(44100, 1));
            waveOut.Init(bufferedWaveProvider);
            waveOut.Play();
            
            foreach (var chunk in recordedChunks)
            {
                bufferedWaveProvider.AddSamples(chunk, 0, chunk.Length);
            }

            while (waveOut.PlaybackState == PlaybackState.Playing)
            {
                Thread.Sleep(100);
            }
        }
    }

The recorded sound (in recordedChunks) plays back, but neither the while loop terminates nor is the waveOut.PlaybackStopped callback activated.

Have tried this:

using (var waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))

but it seems to fail for me as the original code above.

What is wrong with this? All help appreciated. (And also, oddly, I thought this worked last week, but now it doesn't? Perhaps I am mistaken!)


Solution

  • BufferedWaveProvider is a never-ending stream. It always provides audio to read even if that is silent. So playback will never end.

    You can change this by setting the ReadFully property to false. But you will also need to change your code above to write into the BufferedWaveProvider before you start playing.

    Also BufferedWaveProvider uses a circular buffer behind the scenes. It is intended for situations where audio is being added in real-time. So be careful not to overflow the buffer if you're adding everything in one go.