How to Record audio from microphone in C#

By FoxLearn 11/16/2024 3:10:14 AM   782
To record audio from a microphone in C#, you can use the NAudio library, which is a popular library for working with audio in .NET.

NAudio is an open source .NET audio library written by Mark Heath. Here's a basic example of how you can record audio from a microphone using NAudio:

How to record audio from microphone in C#

NAudio support multiple features:

  1. Play back audio using a variety of APIs (WaveOut, DirectSound, ASIO, WASAPI)
  2. Read audio from many standard file formats (WAV, AIFF, MP3, G.711 mu-law and a-law, ADPCM, G.722, Speex (using NSpeex),WMA, AAC, MP4 and more)
  3. Convert between various forms of uncompressed audio (Change the number of channels - Mono to stereo, stereo to mono, Modify bit depth (8, 16, 24, 32 integer or 32 bit IEEE float), Resample audio using a choice of resampling algorithms)
  4. Encode audio using any ACM or Media Foundation codec installed on your computer (Create MP3s (Windows 8 and above), AAC/MP4 audio (Windows 7 and above), WMA  WAV files containing G.711, ADPCM, G.722, etc.)
  5. Mix and manipulate audio streams using a 32-bit floating mixing engine
  6. Record audio using a variety of capture APIs (WaveIn, WASAPI, ASIO)
  7. Record system audio with WASAPI Capture
  8. Work with soundcards (Enumerate devices, Access soundcard controls and metering information)
  9. Full MIDI event model (Read and write MIDI files, Respond to received MIDI events, Send MIDI events)
  10. An extensible programming model (All base classes easily inherited from for you to add your custom components)
  11. Support for UWP (Create Windows 8 Store apps and Windows Universal apps)

First, You can design a simple UI as shown below, then you need to install the NAudio package from NuGet if you haven't already.

If you install it via NuGet Package Manager Console

Install-Package NAudio

You can also install NAudio via Nuget by right clicking on your project, then select Manage NuGet Packages. Next, Enter NAudio at the search box => Install

c# naudio

C# record audio from microphone

Here's a simple c# record audio from microphone, we will record audio from our microphone then save it to a WAV file.

c# record audio from microphone

Open your form, then add your code as shown below

//c# record audio microphone
WaveInEvent _waveSource;
static WaveFileWriter _waveFileWriter;

Double-click on Record button, then add a click event handler to handle record audio

//c# record audio from microphone
private void btnRecord_Click(object sender, EventArgs e)
{
    // Set the desired audio format
    _waveSource.WaveFormat = new WaveFormat(44100, 1); // 44.1kHz, mono

    // Set up an event handler to capture the recorded data
    _waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);

    // Set up the path to save the recorded audio file
    string outputFilePath = $"{Application.StartupPath}\\audio.wav";

    // Set up a WaveFileWriter to write the recorded data to a file
    _waveFileWriter = new WaveFileWriter(outputFilePath, _waveSource.WaveFormat);

    lblStatus.Text = "Status: Recording...";

    // microphone c# record audio
    // Start recording
    _waveSource.StartRecording();
}

Double-click on Stop button, then add a click event handler to handle stop record audio

private void btnStop_Click(object sender, EventArgs e)
{
    // Stop recording
    _waveSource.StopRecording();
    lblStatus.Text = "Status: Recording stopped";
}

Double-clicking on Open button, then add a click event handler to handle open record audio file

private void btnOpen_Click(object sender, EventArgs e)
{
    string fileName = $"{Application.StartupPath}\\audio.wav";
    if (File.Exists(fileName))
    {
        SoundPlayer soundPlayer = new SoundPlayer(fileName);
        soundPlayer.Play();
    }
}

Double-click on your Form , then add a Form_Load event handler to handle create a WaveInEvent

private void Form2_Load(object sender, EventArgs e)
{
    // Set up the WaveInEvent to record from the default sound device
    _waveSource = new WaveInEvent();
}

Add a FormClosing event handler to help you dispose your objects

private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
    // Clean up resources
    if (_waveFileWriter != null)
        _waveFileWriter.Dispose();
    if (_waveSource != null)
        _waveSource.Dispose();
}
// Event handler to handle the recorded audio data
private static void waveSource_DataAvailable(object sender, WaveInEventArgs e)
{
    // Write the recorded audio data to the WaveFileWriter
    _waveFileWriter.Write(e.Buffer, 0, e.BytesRecorded);
    _waveFileWriter.Flush();
}

In this example:

- We create a WaveInEvent object to capture audio from the default sound device, then we set the desired audio format (44.1kHz sample rate, mono).

- Next, We set up an event handler waveSource_DataAvailable to handle the recorded audio data.

- We start recording when click on Record button.

- We stop recording when click on Stop button.

- We open recording file when click on Open button.

- Finally, we clean up the resources and close the program.

Make sure to handle exceptions appropriately and add error checking where necessary, especially when dealing with file I/O operations and audio devices.