Hearing the Incoming audio from mic

こ雲淡風輕ζ 提交于 2019-11-30 16:56:21

Sample code as promised. Code is for a form with two buttons (named StartBtn and StopBtn).

public partial class Form1 : Form
{
    private WaveIn waveIn = null;
    private BufferedWaveProvider waveProvider = null;
    private WaveOut waveOut = null;

    public Form1()
    {
        InitializeComponent();
    }

    private void StartBtn_Click(object sender, EventArgs e)
    {
        if (waveIn != null)
            return;

        // create wave input from mic
        waveIn = new WaveIn(this.Handle);
        waveIn.BufferMilliseconds = 25;
        waveIn.RecordingStopped += waveIn_RecordingStopped;
        waveIn.DataAvailable += waveIn_DataAvailable;

        // create wave provider
        waveProvider = new BufferedWaveProvider(waveIn.WaveFormat);

        // create wave output to speakers
        waveOut = new WaveOut();
        waveOut.DesiredLatency = 100;
        waveOut.Init(waveProvider);
        waveOut.PlaybackStopped += wavePlayer_PlaybackStopped;

        // start recording and playback
        waveIn.StartRecording();
        waveOut.Play();
    }

    void waveIn_DataAvailable(object sender, WaveInEventArgs e)
    {
        // add received data to waveProvider buffer
        if (waveProvider != null)
            waveProvider.AddSamples(e.Buffer, 0, e.BytesRecorded);
    }

    private void StopBtn_Click(object sender, EventArgs e)
    {
        if (waveIn != null)
            waveIn.StopRecording();
    }

    void waveIn_RecordingStopped(object sender, StoppedEventArgs e)
    {
        // stop playback
        if (waveOut != null)
            waveOut.Stop();

        // dispose of wave input
        if (waveIn != null)
        {
            waveIn.Dispose();
            waveIn = null;
        }

        // drop wave provider
        waveProvider = null;
    }

    void wavePlayer_PlaybackStopped(object sender, StoppedEventArgs e)
    {
        // stop recording
        if (waveIn != null)
            waveIn.StopRecording();

        // dispose of wave output
        if (waveOut != null)
        {
            waveOut.Dispose();
            waveOut = null;
        }
    }
}

Note especially the waveIn.BufferMilliseconds and waveOut.DesiredLatency settings to reduce the lag times.

For compressing the data for network transmission I suggest using a different library to process the data blocks. You might need to tune the BufferMilliseconds value to reduce the overheads and get better compression ratios.

The Opus Codec looks like a reasonable option, with Opus.NET for C#.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!