即时将原始音频字节从 NAudio 转换为 wav 字节

Converting Raw audio bytes from NAudio to wav bytes on the fly

您好,我正在尝试使用 NAudio 打开扬声器的实时流,然后以 wav 格式播放它们。我正在使用以下代码

private void ProcessData(object sender, WaveInEventArgs e)
{
    if (e.BytesRecorded > 0)
    {
        MemoryStream stream = new MemoryStream();
        WaveFormat format = WaveFormat.CreateALawFormat(CaptureInstance.WaveFormat.SampleRate, CaptureInstance.WaveFormat.Channels);
        
        using (WaveFileWriter writer = new WaveFileWriter(new IgnoreDisposeStream(stream), format))
        {
            //important i am writing the bytes on the fly to the wavefilewriter
            writer.Write(e.Buffer, 0, e.BytesRecorded);
            writer.Flush();
            writer.Dispose();
            //after dispose i assume the wave file chunk is ready to be read/send
        }

        using (var player = new WaveOutEvent())
        {
            using (var reader = new WaveFileReader(stream))
            {
                //to test the wav bytes i tried to play the bytes but it gives error
                //Not a WAVE file - no RIFF header
                player.Init(reader);
                player.Play();
            }
        
        }
    }
}

但它抛出错误“不是 wav 文件,RIFF header 不存在”,我知道要从原始字节播放实时音频,NAudio 文档中已经显示了另一种方法,但请注意测试字节的可靠性,我正在播放字节并测试 wavefilewriter。实际目的不是播放音频,而是在确认后将正确的 wav 字节发送到服务器进行处理,例如它开始播放然后我将在流中使用 ByteArray。

您需要将 MemoryStream 重新定位到开头以便用 WaveFileReader 阅读它。