I have a program that takes in mp3 data in a byte array. It has to convert that mp3 data into wav format and store it in a byte data. I am trying to use NAudio for this purpose. I am using the following code for this purpose.
Stream inputStream = ...;
Stream outputStream = ...;
using (WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(inputStream)))
using (WaveFileWriter waveFileWriter = new WaveFileWriter(outputStream, waveStream.WaveFormat))
{
byte[] bytes = new byte[waveStream.Length];
waveStream.Read(bytes, 0, waveStream.Length);
waveFileWriter.WriteData(bytes, 0, bytes.Length);
waveFileWriter.Flush();
}
When I run the above code, all I receive is 0 in the byte array. But if use WaveFileWriter to write the data directly to a file, the file receives the correct data. Any reasons?
Give this a try:
If you are writing to a
MemoryStream
, you need to be aware thatWaveFileWriter
will dispose thatMemoryStream
after you dispose theWaveFileWriter
.Here's a workaround using the
IgnoreDisposeStream
. (Also note thatWaveFormatConversionStream.CreatePcmStream
is unnecessary -Mp3FileReader
already returns PCM fromRead
). I also prefer to read in smaller chunks that trying to pass through the whole file.