如何使用C#/ WPF录制音频?

我有一个应用程序,我想添加直接从某种麦克风设备导入小音频片段的function。

我已经允许导入图片,这对于磁盘文件和摄像头来说还可以,因为当你附加它们时,摄像机会神奇地变成磁盘设备,因此文件导入方法适用于两者。

但音频略有不同。 我已经允许从磁盘导入音频文件,但我想添加从麦克风直接录制到磁盘文件或内存缓冲区的function。

C#/ WPF提供了一种简单的方法吗? 添加此function的好方法是什么?

可能最简单的方法是使用mciSendString函数:

public class Program { [DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] private static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback); static void Main(string[] args) { mciSendString("open new Type waveaudio Alias recsound", "", 0, 0); mciSendString("record recsound", "", 0, 0); Console.WriteLine("recording, press Enter to stop and save ..."); Console.ReadLine(); mciSendString("save recsound c:\\work\\result.wav", "", 0, 0); mciSendString("close recsound ", "", 0, 0); } } 

另一个选择是使用DirectShowNet库(有一个名为PlayCap的示例 )。

您可能还会发现此CodeProject文章很有用。

这可能有所帮助。 它将使用开源NAuodio项目……

http://channel9.msdn.com/coding4fun/articles/NET-Voice-Recorder

🙂

我正在使用这个库: http : //www.codeproject.com/KB/cs/Streaming_wave_audio.aspx主要是由于简单的api。 但我不太喜欢这段代码。 例如,它将缓冲区内的缓冲区长时间修复,而不是分配非托管缓冲区。

mciSendString函数仅记录麦克风声音。 如果没有连接麦克风,它将不记录任何内容。