C#实现电脑麦克风录音

本实例通过Naudio库完成麦克风录音并把PCM脉冲信号保存成wav音频文件。关于音频的采样率、比特率、声道等问题请查阅相关资料,本示例不做解释。Naudio库 请从NuGet搜索并下载。
【C#实现电脑麦克风录音】录音接口类:

public interface ISpeechRecorder{void SetFileName(string fileName); void StartRec(); void StopRec(); }

录音实现类:
using System; using NAudio.Wave; namespace Test{class NAudioRecorder : ISpeechRecorder{public WaveIn waveSource = null; public WaveFileWriter waveFile = null; private string fileName = string.Empty; /// /// 第二步:开始录音/// public void StartRec(){try{waveSource = new WaveIn(); //保证电脑有麦克接入否则报错。waveSource.WaveFormat = new WaveFormat(16000, 16, 1); // 16KHz,16bit,单声道的录音格式waveSource.DataAvailable += new EventHandler(waveSource_DataAvailable); waveSource.RecordingStopped += new EventHandler(waveSource_RecordingStopped); waveFile = new WaveFileWriter(fileName, waveSource.WaveFormat); waveSource.StartRecording(); }catch(Exception e){throw new Exception(e.Message); }}/// /// 第三步:停止录音/// public void StopRec(){waveSource.StopRecording(); // Close Wave(Not needed under synchronous situation)if (waveSource != null){waveSource.Dispose(); waveSource = null; }if (waveFile != null){waveFile.Dispose(); waveFile = null; }}/// /// 第一步:设置录音结束后保存的文件路径/// /// 保存wav文件的路径名public void SetFileName(string fileName){this.fileName = fileName; }/// /// 开始录音回调函数/// /// /// private void waveSource_DataAvailable(object sender, WaveInEventArgs e){if (waveFile != null){waveFile.Write(e.Buffer, 0, e.BytesRecorded); waveFile.Flush(); }}/// /// 录音结束回调函数/// /// /// private void waveSource_RecordingStopped(object sender, StoppedEventArgs e){if (waveSource != null){waveSource.Dispose(); waveSource = null; }if (waveFile != null){waveFile.Dispose(); waveFile = null; }}}}

调用方法:
NAudioRecorder nar=new NAudioRecorder(); nar.SetFileName(@"d:\naudio.wav"); nar.StartRec(); nar.StopRec();

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读