How to Record voice in C#

By FoxLearn 7/18/2024 7:45:55 AM   10.06K
To record audio from a microphone in C# Windows Forms Application, you can use the Win32 API

To record audio from a microphone in C# using the Win32 API, you can use the waveIn functions provided by the Windows Multimedia API.

How to record audio from microphone in C#

Here's a basic example of how to record audio in c#.

Drag and drop the Button controls 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 audio

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;
// Delegate for the callback function
[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;

This code sets up a basic audio recording using the Win32 waveIn functions. When you run the program, it will start recording audio from the default microphone until you click the Stop button to stop, you can also record and save the record audio to your disk.