user523234
user523234

Reputation: 14834

NAudio: WaveInEvent handler not working on its own thread

I have this class called AudioInput:

class AudioInput
{
    private WaveIn waveIn;
    public delegate void DataAvailableEventHandler(byte[] data, int size);
    private DataAvailableEventHandler dataAvailableProc;

    public AudioInput(DataAvailableEventHandler dataHandlerProc)
    {
        dataAvailableProc = dataHandlerProc;
    }
    private void initWaveInMic()
    {
        Console.WriteLine("initWaveInMic");
        waveIn = new WaveIn();
        waveIn.BufferMilliseconds = 50;
        waveIn.DeviceNumber = 0;
        waveIn.WaveFormat = new WaveFormat(8000, 1);
        waveIn.DataAvailable += new EventHandler<WaveInEventArgs>(waveIn_DataAvailable);
        waveIn.StartRecording();
    }
    void waveIn_DataAvailable(object sender, WaveInEventArgs e)
    {
        Console.WriteLine("waveIn_DataAvailable e.buffer length: {0}", e.Buffer.Length);
        dataAvailableProc(e.Buffer, e.Buffer.Length);
    }
     public void startNAudio()
    {
        this.initWaveInMic();  //start mic wavein
    }
}

From the calling class:

public partial class AudioTest : Form
{
    Thread audioInputThread;
    AudioInput audioInput;

    private void audioInputCreateThread()
    {
        audioInput = new AudioInput(audioDataToSend);
        audioInput.startNAudio();
        Console.WriteLine("audioInputCreateThread at the end");
    }

    private void AudioTest_Load(object sender, EventArgs e)
    {
        // this will work
        //audioInputCreateThread();

        //this will not work
        audioInputThread = new Thread(audioInputCreateThread);
        audioInputThread.Start();
    }

    private void audioDataToSend(byte[] data, int size)
    {
        Console.WriteLine("audioDataToSend size: {0}", size);
    }
}

The waveIn_DataAvailable callback in the AudioInput class is not getting called. Any suggestions what I did wrong?

Upvotes: 1

Views: 3447

Answers (1)

Mark Heath
Mark Heath

Reputation: 49492

The WaveInEvent class should be used in this instance. It will create its own background thread, and use a SyncContext to marshal callbacks onto the GUI thread if possible.

Upvotes: 1

Related Questions