Search code examples
c#wpfaudionaudio

C# NAudio: Recorded file wont play


I'm trying to record my voice and, upon stopping the recording, have a save file dialog pop up. I can do this and save it to my desktop for playback. Unfortunately Groove won't recognize the file (stating that it can't play), and I'm positive it's not a fault on their part.

Please excuse the comments, and the code dump.

public partial class RecordAndEditVoice : Window
{
 WaveIn sourceStream = null;
    WaveFileWriter waveWriter = null;
      SaveFileDialog save = new SaveFileDialog();

     private void sourceStream_DataAvailable(object sender, WaveInEventArgs e)
    {
        if (waveWriter == null) return;
        //Adds bytes to the wave file, storing them in a buffer? 
        waveWriter.Write(e.Buffer, 0, e.BytesRecorded);
        waveWriter.Flush();
    }

    private void recordButton_Click(object sender, RoutedEventArgs e)
    {


        MainWindow mw = new MainWindow();
        int devNum = mw.DeviceButton();

        if (recordButton.Content.ToString() == "RECORD")
        {
            recordButton.Content = "STOP";
            //Start recording audio. 
            sourceStream = new WaveIn();

            sourceStream.DeviceNumber = devNum;

            //1. Set the sample rate. 2. Get number of channels supported on the device.
            sourceStream.WaveFormat = new WaveFormat(44100, WaveIn.GetCapabilities(devNum).Channels);



            sourceStream.StartRecording();

            sourceStream.DataAvailable += new EventHandler<WaveInEventArgs>(sourceStream_DataAvailable);


        }
        else if(recordButton.Content.ToString() == "STOP")
        {

            sourceStream.StopRecording();
            save.Filter = "Wave Files (*.wav)|*.wav;";
            if (save.ShowDialog() != true) return;

            waveWriter = new WaveFileWriter(save.FileName, sourceStream.WaveFormat);


            recordButton.Content = "RECORD";



        }
    }
}

I tried moving the waveWriter into the if statement but it throws an exception of type 'System.ArgumentException'. Which when googled is referenced too broadly to be of much help.


Solution

  • You must call Dispose on WaveFileWriter before you have a playable file. This is because the WAV file format includes some length information at the start of the file that is only filled in when you call Dispose