1

我有一个名为 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
    }
}

从调用类:

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);
    }
}

AudioInput 类中的 waveIn_DataAvailable 回调没有被调用。任何建议我做错了什么?

4

1 回答 1

1

在这种WaveInEvent情况下应该使用该类。它将创建自己的后台线程,并尽可能使用 SyncContext 将回调编组到 GUI 线程上。

于 2012-11-14T06:50:53.717 回答