如何解码RTP数据包并保存它有.wav文件

时间:2011-08-05 05:45:09

标签: c# sip rtp naudio wav

我正在尝试开发一个应用程序,在该应用程序中建立SIP呼叫,然后我捕获rtp音频数据包。因为它们是编码所以我需要解码它们并保存它有.wav文件。尝试使用NAudio但没有奏效。有没有使用NAudio或任何其他来源解决这个问题的解决方案...

我使用的代码如下。 data是rtp数据包数据所在的字节数组。

System.IO.MemoryStream stream = new System.IO.MemoryStream(data);

RawSourceWaveStream rsws = new RawSourceWaveStream(stream, WaveFormat.CreateMuLawFormat(8000,1));

WaveStream conversionStream = WaveFormatConversionStream.CreatePcmStream(rsws);

WaveStream blockAlignedStream = new BlockAlignReductionStream(conversionStream);

byte[] buffer = new byte[udpHeader.Data.Length];
blockAlignedStream.Read(buffer, 0, udpHeader.Data.Length);
writer.WriteData(buffer, 0, buffer.Length);

先谢谢。

1 个答案:

答案 0 :(得分:0)

迟到总比没有好!

使用Mark Heath的以下助手类 从 Using NAudio to decode mu-law audio

    public class RawSourceWaveStream : WaveStream
    {
        private Stream sourceStream;
        private WaveFormat waveFormat;

        public RawSourceWaveStream(Stream sourceStream, WaveFormat waveFormat)
        {
            this.sourceStream = sourceStream;
            this.waveFormat = waveFormat;
        }

        public override WaveFormat WaveFormat
        {
            get { return this.waveFormat; }
        }

        public override long Length
        {
            get { return this.sourceStream.Length; }
        }

        public override long Position
        {
            get
            {
                return this.sourceStream.Position;
            }
            set
            {
                this.sourceStream.Position = value;
            }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            return sourceStream.Read(buffer, offset, count);
        }
    }

获取最新的NAudio.dll和NAudio.WindowsMediaFormat.dll

来自

http://naudio.codeplex.com/

然后执行以下操作将U-Law或Mu-Law转换为Wav:

Stream tmpMemStream = new FileStream(Server.MapPath("/input/") + "input.voc", FileMode.Open, FileAccess.Read);
var waveFormat = WaveFormat.CreateMuLawFormat(8000, 1);  // Feel free to tweak this number
var reader = new RawSourceWaveStream(tmpMemStream, waveFormat);
using (WaveStream convertedStream = WaveFormatConversionStream.CreatePcmStream(reader))
{
    WaveFileWriter.CreateWaveFile(Server.MapPath("/output/") + "output.wav", convertedStream);
}
tmpMemStream.Close();

请记住尊重这些音频文件所有者的隐私!