c# NAudio:录制的文件不播放

本文关键字:文件 播放 NAudio | 更新日期: 2023-09-27 18:10:52

我正在录制我的声音,在停止录制时,有一个保存文件对话框弹出。我可以这样做,并将其保存到我的桌面以供回放。不幸的是,Groove无法识别该文件(说明它无法播放),我确信这不是他们的错误。

请原谅注释和代码转储。

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";

        }
    }
}

我尝试将waveWriter移动到if语句中,但它抛出了类型为"System.ArgumentException"的异常。这句话在谷歌上被广泛引用,没有多大帮助。

c# NAudio:录制的文件不播放

你必须在WaveFileWriter上调用Dispose才能得到一个可播放的文件。这是因为WAV文件格式在文件的开头包含一些长度信息,只有在调用Dispose

时才填充。