Search code examples
c#wavnaudio

Using NAudio to mix WaveProviders


I'm using NAudio to generate and play sound waves in runtime.

I've managed to get a sine wave generated using this tutorial: http://mark-dot-net.blogspot.com/2009/10/playback-of-sine-wave-in-naudio.html

However - what I really need is to be able to add many individual waves to a WaveMixerStream, in runtime.

I understand that to do this I need individual WaveStreams but I don't know how to turn the output from WaveProvider into a WaveStream to add to the WaveMixerStream.

I assume this isn't possible so altered the code to give a derived WaveStream Class.

I've added:

public override long Length
    {
        get { return long.MaxValue; }
    }

But I'm not sure how to get the position:

public override long Position
{
    get
    {
        return //What here?
    }
    set
    {
        // What here? = value;
    }

}

So the question is: 1. Will this work? 2. How do I get/set position?

Thanks in advance.


Solution

  • The difference between IWaveProvider and WaveStream is that WaveStream supports reporting length and position and setting position. However, since you are passing in IWaveProvider, you don't know the length and you can't set the position. Simply do nothing in the Position setter, and for the Position getter, return the total number of bytes that have been returned from the Read method so far (just have a private variable of type long to store this).

    Another approach is simply to copy the code from WaveMixerStream and make it into an IWaveProvider instead of a WaveStream. This will actually simplify it quite a bit, A lot of the complexity of WaveMixerStream is repositioning all the mixer inputs correctly when you reposition.

    (By the way, in the future I will be encouraging people to use the ISampleProvider interface and there is already MixingSampleProvider that does exactly what you want. I've not got round to writing tutorials on this yet, but it is all in there)