2

I want to convert mp3 files to WAV. In DirectX.DirectSound the secondary buffer is supporting only WAV. I am converting the files using naudio and this is working fine.

using (Mp3FileReader reader = new Mp3FileReader(mp3File))
{
    WaveFileWriter.CreateWaveFile(outputFile, reader);
}

The problem is that I can't save the files on disk so I have to use them with stream.

 Mp3FileReader mp3reader = new Mp3FileReader(filenamePathMp3);
 var stream=WaveFormatConversionStream.CreatePcmStream(mp3reader);

which throws an exception Value does not fall within the expected range. How Can I make a stream with the audio converted to WAV or Raw audio for the secondaryBuffer without writing on disk?

Thank you in advance,

Alexandros Mor
  • 127
  • 3
  • 12

2 Answers2

4

WaveFileWriter can write to a Stream instead of a file so you can just pass in a MemoryStream. Also, Mp3FileReader.Read already returns PCM so you could read out into a byte[] and then insert that into your memory stream if you prefer.

Mark Heath
  • 48,273
  • 29
  • 137
  • 194
  • Health This is my code but I am getting the same error ` long count; byte[] info ; using (Mp3FileReader mp3reader = new Mp3FileReader(filenamePathMp3)) { count = mp3reader.Length; info = new byte[count]; mp3reader.Read(info, 0, (int)count); } MemoryStream memstream = new MemoryStream(info); foreGroundSound = new SecondaryBuffer(source: memstream, desc: bufferDescription, parent: sounddevice); ` Any ideas? thank you in advance. – Alexandros Mor Apr 11 '13 at 15:48
  • Will `Mp3FileReader.Read` read whole file or only audio data samples? I want to make a FadeOut and I consider multiplying byes by some value. Will that work? Will I be able to generate new mp3 from result array? – nicks May 22 '15 at 07:07
4

I've achieved to convert MP3 to WAV without writing it to the disk by using MemoryStream and WaveFileWriter.WriteWavFileToStream You can also set up sampleRate bitrate and channel using RawSourceWaveStream

public static byte[] ConvertMp3ToWav(byte[] mp3File)
{
    using (var retMs = new MemoryStream())
    using (var ms = new MemoryStream(mp3File))
    using (Mp3FileReader reader = new Mp3FileReader(ms))
    {
        var rs = new RawSourceWaveStream(reader, new WaveFormat(16000, 1));
        using (WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(rs))
        {
            WaveFileWriter.WriteWavFileToStream(retMs,pcmStream);
            return retMs.ToArray();
        }
    }
}
daniel.szaniszlo
  • 413
  • 5
  • 13