Using NAudio to decode mu-law audio

天涯浪子 提交于 2019-11-27 18:51:20

问题


I'm attempting to use NAudio to decode mu-law encoded audio into pcm audio. My service is POSTed the raw mu-law encoded audio bytes and I'm getting an error from NAudio that the data does not have a RIFF header. Do I need to add this somehow? The code I'm using is:

WaveFileReader reader = new WaveFileReader(tmpMemStream);
using (WaveStream convertedStream = WaveFormatConversionStream.CreatePcmStream(reader))
{
    WaveFileWriter.CreateWaveFile(recordingsPath + "/" + outputFileName, convertedStream);
}

I'm also saving the raw data to the disk and doing the decoding in Matlab which is working with no problem. Thanks.


回答1:


Since you just have raw mu-law data, you can't use a WaveFileReader on it. Instead, create a new class that inherits from WaveStream.

In its Read method, return data from tmpMemStream. As a WaveFormat return a mu-law WaveFormat.

Here's a generic helper class that you could use:

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);
    }
}

Now you can proceed to create the converted file as you did before, passing in the RawSourceWaveStream as your input:

var waveFormat = WaveFormat.CreateMuLawFormat(8000, 1);
var reader = new RawSourceWaveStream(tmpMemStream, waveFormat);
using (WaveStream convertedStream = WaveFormatConversionStream.CreatePcmStream(reader))
{
    WaveFileWriter.CreateWaveFile(recordingsPath + "/" + outputFileName, convertedStream);
}


来源:https://stackoverflow.com/questions/4234665/using-naudio-to-decode-mu-law-audio

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