C# 电脑麦克风录音
本实例通过Naudio库完成麦克风录音并把PCM脉冲信号保存成wav音频文件。关于音频的采样率、比特率、声道等问题请查阅相关资料,本示例不做解释。Naudio库 请从NuGet搜索并下载。
录音接口类:
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;
/// <summary>
/// 第二步:开始录音
/// </summary>
public void StartRec()
{
try
{
waveSource = new WaveIn();//保证电脑有麦克接入否则报错。
waveSource.WaveFormat = new WaveFormat(16000, 16, 1); // 16KHz,16bit,单声道的录音格式
waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);
waveSource.RecordingStopped += new EventHandler<StoppedEventArgs>(waveSource_RecordingStopped);
waveFile = new WaveFileWriter(fileName, waveSource.WaveFormat);
waveSource.StartRecording();
}
catch(Exception e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// 第三步:停止录音
/// </summary>
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;
}
}
/// <summary>
/// 第一步:设置录音结束后保存的文件路径
/// </summary>
/// <param name="fileName">保存wav文件的路径名</param>
public void SetFileName(string fileName)
{
this.fileName = fileName;
}
/// <summary>
/// 开始录音回调函数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void waveSource_DataAvailable(object sender, WaveInEventArgs e)
{
if (waveFile != null)
{
waveFile.Write(e.Buffer, 0, e.BytesRecorded);
waveFile.Flush();
}
}
/// <summary>
/// 录音结束回调函数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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();