private IWaveIn waveIn; private WaveFileWriter writer; /// <summary> /// 开始录音 /// </summary> private void StartRecording() { if (waveIn != null) return; waveIn = new WaveIn {WaveFormat = new WaveFormat(8000, 1)};//设置码率 writer = new WaveFileWriter("test.wav", waveIn.WaveFormat); waveIn.DataAvailable += waveIn_DataAvailable; waveIn.RecordingStopped += OnRecordingStopped; waveIn.StartRecording(); } /// <summary> /// 停止录音 /// </summary> private void StopRecording() { waveIn.StopRecording(); waveIn.Dispose(); } /// <summary> /// 录音中 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void waveIn_DataAvailable(object sender, WaveInEventArgs e) { if (this.InvokeRequired) { this.BeginInvoke(new EventHandler<WaveInEventArgs>(waveIn_DataAvailable), sender, e); } else { writer.Write(e.Buffer, 0, e.BytesRecorded); int secondsRecorded = (int)(writer.Length / writer.WaveFormat.AverageBytesPerSecond);//录音时间获取 if (secondsRecorded >= 30) { StopRecording(); } } } /// <summary> /// 停止录音 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnRecordingStopped(object sender, StoppedEventArgs e) { if (this.InvokeRequired) { this.BeginInvoke(new EventHandler<StoppedEventArgs>(OnRecordingStopped), sender, e); } else { if (waveIn != null) // 关闭录音对象 { waveIn.Dispose(); waveIn = null; } if (writer != null)//关闭文件流 { writer.Close(); writer = null; } if (e.Exception != null) { MessageBox.Show(String.Format("出现问题 {0}", e.Exception.Message)); } } }
上面代码
int secondsRecorded = (int)(writer.Length / writer.WaveFormat.AverageBytesPerSecond)
用这句获取录音时间后,
调用停止录音的方法,
private void StopRecording()
{
waveIn.StopRecording(); 这里报错,未将对像引用到实例
waveIn.Dispose();
}
已经解决,最新的版本的Naudio源代码可能有问题,下载了1.5版本的就可以了。