Search code examples
c#vlcnaudioaudacity

Why does NAudio read zeros to buffer after playing the file but not before?


The following code will successfully, load, play, edit audio samples and (almost) write to audio file. I say almost because when I comment out the "Play" code it works, but leaving it in causes the buffer read:

audioFile.Read(buffer, 0, numSamples);

to result in zeros.

Do I need to reset the audioFile somehow? All the examples I've found don't mention any need for this.

using System;
using NAudio.Wave;

namespace NAudioTest
{
class TestPlayer
{
    static void Main(string[] args)
    {
        string infileName = "c:\\temp\\pink.wav";
        string outfileName = "c:\\temp\\pink_out.wav";

        // load the file
        var audioFile = new AudioFileReader(infileName);

        // play the file
        var outputDevice = new WaveOutEvent();
        outputDevice.Init(audioFile);
        outputDevice.Play();
        //Since Play only means "start playing" and isn't blocking, we can wait in a loop until playback finishes....
        while (outputDevice.PlaybackState == PlaybackState.Playing) { System.Threading.Thread.Sleep(1000); }

        // edit the samples in file
        int fs = audioFile.WaveFormat.SampleRate;
        int numSamples = (int)audioFile.Length / sizeof(float); // length is the number of bytes - 4 bytes in a float

        float[] buffer = new float[numSamples];
        audioFile.Read(buffer, 0, numSamples);

        float volume = 0.5f;
        for (int n = 0; n < numSamples; n++) { buffer[n] *= volume; }

        // write edited samples to new file
        var writer = new WaveFileWriter(outfileName,audioFile.WaveFormat);
        writer.WriteSamples(buffer,0,numSamples);
    }
}

}


Solution

  • You must call Dispose on your writer before it is a valid WAV file. I recommend that you put it in a using block.

    using(var writer = new WaveFileWriter(outfileName,audioFile.WaveFormat))
    {
        writer.WriteSamples(buffer,0,numSamples);
    }