带有 Naudio 和 TCP 流的断断续续的音频。缓冲区满异常

Choppy Audio with Naudio and TCP Stream. Buffer Full Exception

我正在尝试通过 TCP 连接使用 Naudio 流式传输音频。问题是音频听起来不稳定。我相信这是因为当我尝试将样本添加到 bufferedwaveprovider 时出现异常,提示缓冲区已满。

我试过增加缓冲区大小,但结果没有改变。

-----客户端代码-----

    public TcpClient client;
    public WaveOut waveplayer = new WaveOut();
    public BufferedWaveProvider bwp = new BufferedWaveProvider(new WaveFormat(8000, 16, 1));
    public byte[] buffer = new byte[1024 * 16];

    public Form1()
    {
        bwp.BufferLength = 1024 * 16;
        waveplayer.Init(bwp);
        waveplayer.Play();
    }

    public void audio()
    {
        try
        {
            client = new TcpClient(textBox1.Text.ToString(), 8001);
            NetworkStream ns = client.GetStream();
        }
        catch (Exception e)
        {
            MessageBox.Show(e.ToString());
        }

        while (true)
        {
            try
            {
                ns.Read(buffer, 0, buffer.Length);
                bwp.AddSamples(buffer, 0, buffer.Length);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }

-----服务器代码-----

    public NAudio.Wave.WaveInEvent sourcestream = null;
    public TcpListener listener = new TcpListener(IPAddress.Any, 8001);
    public TcpClient client;
    public NetworkStream ns;

    public Form1()
    {
        InitializeComponent();
        sourcestream = new NAudio.Wave.WaveInEvent();
        sourcestream.DeviceNumber = 0;            
        sourcestream.WaveFormat = new NAudio.Wave.WaveFormat(8000, 16, 1);
        sourcestream.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>(audioDataAvailable);
        sourcestream.StartRecording();
    }

    public void acceptclients()
    {
        listener = new TcpListener(IPAddress.Any, 8001);
        listener.Start();
        client = listener.AcceptTcpClient();
        ns = client.GetStream();
    }

    void audioDataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
    {
        try
        {
            if (client.Connected)
            {
                ns.Write(e.Buffer, 0, e.Buffer.Length);
                ns.Flush();
            }
        }
        catch(Exception ex)
        {            

这是我收到的确切错误

"System.InvalidOperationException:缓冲区已满 NAudio.Wave.BufferedWaveProvider.AddSamples(字节 [] 缓冲区,Int32 偏移量,Int32 计数

如果您收到缓冲区已满异常,这意味着音频到达的速度比您播放它的速度快。您要么需要更大的缓冲区大小,要么在下载之前限制音频。

您还应该在服务器端使用 e.BytesRecorded,而不是 e.Buffer.Length。这也可能是您遇到的问题的原因。

另一个错误是您应该检查从 ns.Read 读取的字节数并在调用 bwp.AddSamples

时使用该数字