Windows Forms: Record voice in C#

To record audio from a microphone in C# .NET Windows Forms Application, you can use the Win32 API

Drag the Button control from the visual studio toolbox to your winform, this application allows you to record a voice from the microphone, then save the voice to your hard disk.

c# record voice

You can use Win32 API to record audio from microphone in c#, so you need to import the mciSendStringA method from the Win32 API as the folowing c# code.

string _fileName;

[DllImport("winmm.dll", EntryPoint = "mciSendStringA", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)]
private static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);

Add code to handle the Record button click event allows you to select directory to save file, then record voice in c#.

//c# record audio from microphone
private void btnRecord_Click(object sender, EventArgs e)
{
    using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "Media (.wav)|*.wav" })
    {
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            _fileName = sfd.FileName;
            mciSendString("open new Type waveaudio Alias recsound", "", 0, 0);
            mciSendString("record recsound", "", 0, 0);
            btnStop.Enabled = true;
            btnRecord.Enabled = false;
        }
    }
}

Add code to handle the Stop button click event allows you to stop record audio, then save the voice to your disk.

private void btnStop_Click(object sender, EventArgs e)
{
    mciSendString("save recsound " + _fileName, "", 0, 0);
    mciSendString("close recsound", "", 0, 0);
    btnStop.Enabled = false;
    btnRecord.Enabled = true;
}

Add code to handle the Open button click event allows you to open the voice you recorded.

private void btnOpen_Click(object sender, EventArgs e)
{
    SoundPlayer soundPlayer = new SoundPlayer(_fileName);
    soundPlayer.Play();
}

And don't forget import the namespaces below.

using System.Media;
using System.Runtime.InteropServices;

Press F5 to run your application, then you can record and save the voice to your disk.