我们在开发Windows客户端程序时,有时需要实现录音的功能,比如使用语音识别时。本文中的代码通过DLL导入调用系统API实现了录制16kHz、16bit位宽的单声道wav格式录音。该代码已用于ASRT语音识别客户端SDK(C# WPF桌面版):https://github.com/nl8590687/ASRT_SpeechClient_WPF 。
核心类:WavRecorder类实现 (C#)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace ailemon { public class WavRecorder { [DllImport("winmm.dll", EntryPoint = "mciSendString", CharSet = CharSet.Auto)] public static extern int mciSendString( string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback ); private string _dName = ""; private int bitspersample = 16; //每个样本的比特数,单位:位、比特、bit private int channels = 1; //声道数 private int samplespersec = 16000; //采样频率,单位:Hz public WavRecorder(string dName) { _dName = dName; } public void Record() { mciSendString("open new Type waveaudio Alias " + _dName, "", 0, 0); mciSendString("stop " + _dName, "", 0, 0); int bytespersec = bitspersample * channels * samplespersec / 8; //每秒的字节数 int alignment = bitspersample * channels / 8; //每个时刻样本的字节数 string command = "set " + _dName + " time format ms"; command += " bitspersample " + bitspersample; command += " channels " + channels; command += " samplespersec " + samplespersec; command += " bytespersec " + bytespersec; command += " alignment " + alignment; //command += " set waveaudio format tag pcm"; //command += " set file format wav"; string _mciReturnData = ""; int error = mciSendString(command, _mciReturnData, 0, 0); mciSendString("record " + _dName, "", 0, 0); } public void Stop() { mciSendString("stop " + _dName, "", 0, 0); } public void Save(string filename = "1.wav") { mciSendString("save " + _dName + " " + filename, "", 0, 0); } public void Close() { mciSendString("close " + _dName, "", 0, 0); } public void Play() { //long P1 = 0, P2 = 3000; //mciSendString("seek recsound to", P1.ToString(), 0, 0); mciSendString("seek " + _dName + " to start", "", 0, 0); mciSendString("play " + _dName, "", 0, 0); } } }
调用样例:
using ailemon; … WavRecorder audioRecorder = new WavRecorder(); audioRecorder.Record(); audioRecorder.Stop(); string filename = "speechfile.wav"; audioRecorder.Save(filename); audioRecorder.Play(); audioRecorder.Close();
版权声明本博客的文章除特别说明外均为原创,本人版权所有。欢迎转载,转载请注明作者及来源链接,谢谢。本文地址: https://blog.ailemon.net/2020/08/31/csharp-implement-audio-recorder-by-winmm/ All articles are under Attribution-NonCommercial-ShareAlike 4.0 |