c# Naudio MemoryStream Exception was not readable

822 views Asked by At

I'm using Naudio. And I'm trying to write .mp3 stream to .wav stream. This is my code:

        MemoryStream outputStream = new MemoryStream();                
        WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(@"C:\Users\practice\Desktop\ORIG FILE.mp3"));            
        using (WaveFileWriter waveFileWriter = new WaveFileWriter(outputStream, waveStream.WaveFormat))
        {
            byte[] bytes = new byte[waveStream.Length];
            waveStream.Position = 0;
            waveStream.Read(bytes, 0, (int)waveStream.Length);
            waveFileWriter.Write(bytes, 0, bytes.Length);
            waveFileWriter.Flush();
        }
        using(WaveFileReader reader = new WaveFileReader(outputStream))
        {

        }
        waveStream.Close();
        outputStream.Close();

I've got an exception in the second using block: Stream was not readable. How can I resolve it?

1

There are 1 answers

2
matcheek On BEST ANSWER

When your using statement completes the disposable gets disposed.

You can either combine

        using (MemoryStream outputStream = new MemoryStream())
        using (WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(@"D:\recit.mp3")))
        using (WaveFileWriter waveFileWriter = new WaveFileWriter(outputStream, waveStream.WaveFormat))
        {
            byte[] bytes = new byte[waveStream.Length];
            waveStream.Position = 0;
            waveStream.Read(bytes, 0, (int)waveStream.Length);
            waveFileWriter.Write(bytes, 0, bytes.Length);
            waveFileWriter.Flush();

            outputStream.Position = 0;

            using (WaveFileReader reader = new WaveFileReader(outputStream))
            {}
        }
    }

or translate it into try-catch-finally where you would dispose the streams manually