c#NAudio 录音功能实现
在网上找了很多类似录音教程效果都不好,或根本不能录音,代码由网上借鉴修改(完整实现录音播放功能)
1.首先新建引用类 recordcontroller
public class recordcontroller
{
public wavein mwavin;
public wavefilewriter mwavwriter;
/// <summary>
/// 开始录音
/// </summary>
/// <param name="filepath"></param>
public void startrecord(string filepath)
{
mwavin = new wavein();
mwavin.dataavailable += mwavin_dataavailable;
// mwavin.recordingstopped += mwavin_recordingstopped; 有冲突
mwavwriter = new wavefilewriter(filepath, mwavin.waveformat);
mwavin.startrecording();
}
/// <summary>
/// 停止录音
/// </summary>
public void stoprecord()
{
mwavin?.stoprecording();
mwavin?.dispose();
mwavin = null;
mwavwriter?.close();
mwavwriter = null;
}
//这个方法在调用关闭时会有冲突
private void mwavin_recordingstopped(object sender, stoppedeventargs e)
{
//mwavin?.dispose();
//mwavin = null;
//mwavwriter?.close();
//mwavwriter = null;
}
private void mwavin_dataavailable(object sender, waveineventargs e)
{
mwavwriter.write(e.buffer, 0, e.bytesrecorded);
int secondsrecorded = (int)mwavwriter.length / mwavwriter.waveformat.averagebytespersecond;
}
}
2.在主界面引用 recordcontroller record = new recordcontroller();
/// <summary>
/// 耳机sidetone测试
/// </summary>
/// <param name="i"></param>
public void sidetone(int i)
{
string[] row = getlistviewitem(i);
record.startrecord("e:\\rec.wav");
if (messagebox.show("正在录音,点击是播放录音", "提示", messageboxbuttons.yesno, messageboxicon.information) == dialogresult.no)
{
record.stoprecord();
errorflag = false;
row[6] = "fail";
}
else
{
record.stoprecord();
string path = "e:\\rec.wav";//.wav音频文件路径
system.media.soundplayer player = new system.media.soundplayer(path);
player.play();
if (messagebox.show("是否有录音", "提示", messageboxbuttons.yesno, messageboxicon.information) == dialogresult.no)
{
errorflag = false;
row[6] = "fail";
}
else
{
errorflag = true;
row[5] = "ok";
row[6] = "pass";
}
}
listupdate(row, i);
}
完成代码后测试是能正常录音
下一篇: mac下安装mongodb数据库教程