C#实现录音功能
时间: 2023-07-12 19:04:13 浏览: 71
在 C# 中,可以使用 Windows API MCI (Media Control Interface) 来实现录音功能。以下是一个简单的示例代码,可以录制 WAV 格式的音频文件:
```csharp
using System;
using System.Runtime.InteropServices;
namespace AudioRecorder
{
class Program
{
[DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int mciSendString(string lpCommand, string lpReturnString, int uReturnLength, int hwndCallback);
static void Main(string[] args)
{
string command = "open new Type waveaudio Alias recsound";
mciSendString(command, null, 0, 0);
command = "record recsound";
mciSendString(command, null, 0, 0);
Console.WriteLine("Recording started. Press any key to stop recording...");
Console.ReadKey();
command = "stop recsound";
mciSendString(command, null, 0, 0);
command = "save recsound c:\\audio.wav";
mciSendString(command, null, 0, 0);
command = "close recsound";
mciSendString(command, null, 0, 0);
Console.WriteLine("Recording stopped. Audio file saved to c:\\audio.wav.");
}
}
}
```
在上面的代码中,使用 `mciSendString` 函数发送命令来操作录音设备。首先打开一个新的音频设备,并将其命名为“recsound”。然后发送 “record” 命令开始录音。按任意键停止录音,发送 “stop” 命令停止录音。最后使用 “save” 命令将录制的音频文件保存在 C 盘根目录下,并关闭录音设备。
请注意,此示例代码仅适用于 Windows 操作系统。还应该添加异常处理和错误检查来确保程序的稳定性和可靠性。