问题
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