Recording with NAudio using C#
Asked Answered
F

2

6

I am trying to record audio in C# using NAudio. After looking at the NAudio Chat Demo, I used some code from there to record.

Here is the code:

using System;
using NAudio.Wave;

public class FOO
{
    static WaveIn s_WaveIn;

    static void Main(string[] args)
    {
        init();
        while (true) /* Yeah, this is bad, but just for testing.... */
            System.Threading.Thread.Sleep(3000);
    }

    public static void init()
    {
        s_WaveIn = new WaveIn();
        s_WaveIn.WaveFormat = new WaveFormat(44100, 2);

        s_WaveIn.BufferMilliseconds = 1000;
        s_WaveIn.DataAvailable += new EventHandler<WaveInEventArgs>(SendCaptureSamples);
        s_WaveIn.StartRecording();
    }

    static void SendCaptureSamples(object sender, WaveInEventArgs e)
    {
        Console.WriteLine("Bytes recorded: {0}", e.BytesRecorded);
    }
}

However, the eventHandler is not being called. I am using .NET version 'v2.0.50727' and compiling it as:

csc file_name.cs /reference:Naudio.dll /platform:x86
Falconer answered 8/8, 2011 at 16:45 Comment(0)
A
6

If this is your whole code, then you are missing a message loop. All the eventHandler specific events requires a message loop. You can add a reference to Application or Form as per your need.

Here is an example by using Form:

using System;
using System.Windows.Forms;
using System.Threading;
using NAudio.Wave;

public class FOO
{
    static WaveIn s_WaveIn;

    [STAThread]
    static void Main(string[] args)
    {
        Thread thread = new Thread(delegate() {
            init();
            Application.Run();
        });

        thread.Start();

        Application.Run();
    }

    public static void init()
    {
        s_WaveIn = new WaveIn();
        s_WaveIn.WaveFormat = new WaveFormat(44100, 2);

        s_WaveIn.BufferMilliseconds = 1000;
        s_WaveIn.DataAvailable += new EventHandler<WaveInEventArgs>(SendCaptureSamples);
        s_WaveIn.StartRecording();
    }

    static void SendCaptureSamples(object sender, WaveInEventArgs e)
    {
        Console.WriteLine("Bytes recorded: {0}", e.BytesRecorded);
    }
}
Agley answered 9/8, 2011 at 8:17 Comment(2)
Yes, lack of message loop is the problem. An alternative fix is to use function callbacks.Robustious
How can I save recorded data to an audio file?Psalm
P
1

Just use WaveInEvent instead of WaveIn and the code will work. Then the handling happens on a separate thread instead of in a window message loop, which isn't available in a console application.

Further reading:
https://github.com/naudio/NAudio/wiki/Understanding-Output-Devices#waveout-and-waveoutevent

(The feature was added in 2012, so at the time of the question it wasn't available)

Plummet answered 24/3, 2016 at 19:33 Comment(1)
And how to save the recorded message to a file? [code] wave_in.StartRecording(); Play(); wave_in.StopRecording(); [\code]Psalm

© 2022 - 2024 — McMap. All rights reserved.