Getting data from a microphone in C#

2019-02-04 19:28发布

问题:

I'm trying to record audio data from a microphone (or line-in), and then replay it again, using C#.

Any suggestions on how I can achieve this?

回答1:

have a look at the open source .NET Voice Recorder project which uses NAudio. There is an article on Coding4Fun explaining how it works.



回答2:

See Console and multithreaded recording and playback

class Program
{

    static void Main(string[] args)
    {
        rex.Data += new RecorderEx.DataEventHandler(rex_Data);
        rex.Open += new EventHandler(rex_Open);
        rex.Close += new EventHandler(rex_Close);
        rex.Format = pcmFormat;
        rex.StartRecord();
        Console.WriteLine("Please press enter to exit!");
        Console.ReadLine();
        rex.StopRecord();
    }

    static RecorderEx rex = new RecorderEx(true);
    static PlayerEx play = new PlayerEx(true);
    static IntPtr pcmFormat = AudioCompressionManager.GetPcmFormat(1, 16, 44100);

    static void rex_Open(object sender, EventArgs e)
    {
        play.OpenPlayer(pcmFormat);
        play.StartPlay();
    }

    static void rex_Close(object sender, EventArgs e)
    {
        play.ClosePlayer();
    }

    static void rex_Data(object sender, DataEventArgs e)
    {
        byte[] data = e.Data;
        play.AddData(data);
    }
}