使用C#处理麦克风和扬声器

时间:2013-05-29 10:13:57

标签: c# rtp multimedia

我需要使用RTP组播协议进行语音聊天,所以我需要一个C#dll库,它可以处理扬声器和麦克风以获取用户声音并通过网络发送。 建议使用简单且非常简单的库,使用c#。

1 个答案:

答案 0 :(得分:0)

使用NAudio.dll库,我们可以使用C#处理麦克风和扬声器,代码如下: 1-此代码将为我们提供麦克风设备。

        List<NAudio.Wave.WaveInCapabilities> sources = new List<NAudio.Wave.WaveInCapabilities>();
        for (int i = 0; i < NAudio.Wave.WaveIn.DeviceCount; i++)
        {
            sources.Add(NAudio.Wave.WaveIn.GetCapabilities(i));
        }
        sourceListView.Items.Clear();

        foreach (var source in sources)
        {
            ListViewItem item = new ListViewItem(source.ProductName);
            item.SubItems.Add(new ListViewItem.ListViewSubItem(item, source.Channels.ToString()));
            sourceListView.Items.Add(item);
        }

2-此代码将开始从麦克风捕获音频并将其发送给扬声器。

    private NAudio.Wave.WaveIn sourceStream = null;
    private NAudio.Wave.DirectSoundOut waveOut = null;

    private void btnStart_Click(object sender, EventArgs e)
    {
        if (sourceListView.SelectedItems.Count == 0) return;
        //NAudio.Wave.MixingWaveProvider32 mixer=sourceStream.GetMixerLine();
        int deviceNumber = sourceListView.SelectedItems[0].Index;
        sourceStream = new NAudio.Wave.WaveIn();
        sourceStream.DeviceNumber = deviceNumber;
        sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(9600,8, NAudio.Wave.WaveIn.GetCapabilities(deviceNumber).Channels);
        NAudio.Wave.WaveInProvider waveIn = new NAudio.Wave.WaveInProvider(sourceStream);
        waveOut = new NAudio.Wave.DirectSoundOut();
        waveOut.Init(waveIn);
        sourceStream.StartRecording();
        sourceStream.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>(sourceStream_DataAvailable);
        waveOut.Play();
    }

    void sourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
    {

    }

    private void btnStop_Click(object sender, EventArgs e)
    {
        if (waveOut != null)
        {
            waveOut.Stop();
            waveOut.Dispose();
            waveOut = null;
        }
        if (sourceStream != null)
        {
            sourceStream.StopRecording();
            sourceStream.Dispose();
            sourceStream = null;
        }
    }

这是一个非常简单的例子,你可以从这个网站下载NAudio.dll库: http://naudio.codeplex.com/releases/view/79035