This project has moved. For the latest updates, please go here.

Creating a .wav file from WaveProvider32

Feb 13, 2015 at 7:50 PM
Hello,

I've been writing some code based on the "Play a Sine Wave" example, here:

http://mark-dot-net.blogspot.co.uk/2009/10/playback-of-sine-wave-in-naudio.html

My code is working very nicely, but I want to be able to save the generated sound to a .wav file, and I can't seem to find the right magic spell to get this to work.

Could anyone point me in the right direction, or provide some extra code for the above example that will allow the sine wave sound to be written to a .wav file?

Many thanks,

Adam.
Coordinator
Feb 13, 2015 at 7:54 PM
you can use WaveFileWriter to create a WAV file. Read from the sine wave provider and write into the WaveFileWriter. Just remember that the sine provider will never end so stop writing when you have enough
Marked as answer by AdamDawes575 on 2/13/2015 at 1:17 PM
Feb 13, 2015 at 8:17 PM
Thanks for the quick reply, Mark, I've got this working now. For the benefit of anyone else reading this, here's how I did it:

I declared a class-level WaveFileWriter object named "writer" in my SineWaveProvider32 class. I then added a new method to the class:
    /// <summary>
    /// Start recording audio to the specified .wav file
    /// </summary>
    /// <param name="filename"></param>
    public void StartRecording(string filename)
    {
        writer = new NAudio.Wave.WaveFileWriter(filename, this.WaveFormat);
    }
This gets called from my form and tells it to instantiate the writer and set its filename. Make sure to call this after first calling the SetWaveFormat method.

Then in the Read method, I added the following code, just after the end of the for() loop:
        // Do we have a writer object?
        if (writer != null)
        {
            // Yes, so write the samples we've just added to the file
            writer.WriteSamples(buffer, 0, sampleCount);

            // Have we reached the termination point?
            if (sample > 20000)
            {
                // Yes, so dispose of and remove the writer
                writer.Dispose();
                writer = null;
            }
        }
This stops after generating ~20,000 samples, of course the dispose section can be adjusted to terminate under whatever circumstances are needed.

I'm having a huge amount of fun playing with NAudio, by the way, thank you so much for creating it!

Best regards,

Adam.
Coordinator
Feb 13, 2015 at 8:26 PM
awesome, glad you got it working