2
votes

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,

2

2 Answers

3
votes

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.

1
votes

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