c#Naudio MemoryStream异常无法读取

时间:2015-06-15 11:29:09

标签: c# naudio

我正在使用Naudio。我正在尝试将.mp3流写入.wav流。这是我的代码:

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

我在第二个使用块中遇到异常:Stream was not readable.我该如何解决?

1 个答案:

答案 0 :(得分:1)

当你的使用声明完成时,一次性物品被处理掉。

你可以结合使用

        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))
            {}
        }
    }

或将其翻译成try-catch-finally,您可以手动配置流