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

问题描述:

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

I have an application to which I want to add the ability to import small audio snippets directly from a microphone device of some sort.

我已经允许导入图片,这适用于磁盘文件和相机,因为当您附加它们时,相机会神奇地变成磁盘设备,因此文件导入方法适用于两者.

I already allow importing of pictures and this works okay with disk files and cameras since cameras magically become disk devices when you attach them so a file import method works for both.

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

Audio however is slightly different. I've already allowed for importing audio files off the disk but I want to add the capability to directly record from a microphone to a disk file or in-memory buffer.

C#/WPF 是否提供了一种简单的方法来做到这一点?添加此功能的好方法是什么?

Does C#/WPF provide an easy way to do this? What's a good way to add this functionality?

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

Probably the easiest is to use mciSendString function:

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 库(有一个 sample 称为 PlayCap).

Another option is to use the DirectShowNet library (there's a sample called PlayCap).

您可能还会发现这篇 CodeProject 文章很有用.

You might also find this CodeProject article useful.