使用NAudio录音时节目挂起并保存

时间:2014-12-24 23:06:06

标签: c# naudio

我在使用NAudio保存录音时遇到了一些问题。大多数时候,以下代码都可以使用。在按下"开始录制"后,它将开始录制并保存到.wav文件。按下按钮,然后在按下"停止"按钮。但有时候,单击录制按钮后程序就会挂起。我必须等待大约30秒才开始正确录制。

    private WaveIn waveSource = null;
    private WaveFileWriter waveFile = null;

    private void recordButton_Click(object sender, EventArgs e)
    {
        recordButton.Enabled = false;
        stopRecordButton.Enabled = true;
        waveSource = new WaveIn();
        waveSource.WaveFormat = new WaveFormat(44100, 1);
        waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);
        waveSource.RecordingStopped += new EventHandler<StoppedEventArgs>(waveSouce_RecordingStopped);

        waveFile = new WaveFileWriter("test.wav", waveSource.WaveFormat);
        waveSource.StartRecording();
    }

    private void stopRecordButton_Click(object sender, EventArgs e)
    {
        stopRecordButton.Enabled = false;
        waveSource.StopRecording();
    }     

    private void waveSource_DataAvailable(object sender, WaveInEventArgs e)
    {
        if (waveFile != null)
        {
            waveFile.Write(e.Buffer, 0, e.BytesRecorded);
            waveFile.Flush();
        }
    }

    private void waveSouce_RecordingStopped(object sender, StoppedEventArgs e)
    {
        DisposeWave();
    }

    private void DisposeWave()
    {
        if (waveSource != null)
        {
            waveSource.Dispose();
            waveSource = null;
        }
        if (waveFile != null)
        {
            waveFile.Dispose();
            waveFile = null;
        }
    }

我在visual studio中设置了一个休息时间,发现它在线上挂起:waveSource.StartRecording(); 步入函数大约需要30秒:private void waveSource_DataAvailable()。

我也在另一台计算机上运行了这个程序,但是在点击&#34;开始录制&#34;之后我收到了以下异常文本。按钮。我检查了该计算机上的设备管理器,我非常确定声卡已正确安装。

************** Exception Text **************
NAudio.MmException: BadDeviceId calling waveInOpen
  at NAudio.Wave.WaveIn.OpenWaveInDevice()
  at NAudio.Wave.WaveIn.StartRecording()
  at ToeflSpeaking.MainForm.StartRecordingState() in c:\MyProgram\Toefl Speaking\code\MainForm.cs:line 268
  at ToeflSpeaking.MainForm.timer_Tick(Object sender, EventArgs e) in c:\MyProgram\Toefl Speaking\code\MainForm.cs:line 407
  at System.Windows.Forms.Timer.OnTick(EventArgs e)
  at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message& m)
  at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

0 个答案:

没有答案