在memoryStream之后配置writer

时间:2015-06-24 10:00:48

标签: c# stream naudio

这是我的一段代码:

private static MemoryStream outputStream;


public static void ConvertMp3ToWavStream(string inputPath)
        {                           
            outputStream = new MemoryStream();
            using (Mp3FileReader reader = new Mp3FileReader(inputPath))
            {
                using (WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(reader))
                {
                    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();                    
                }
            }                
        }

这是我的CloseAndDispose方法,我在一些操作之后调用它:

private static void CloseAndDispose()
        {
            if (outputStream != null)
            {
                outputStream.Close();
                outputStream.Dispose();
            }
        }

问题:在所有操作之后,我在内存堆栈中有一些内存,但没有处理掉。据我了解,这是我的writer。当我试图处理作家时,我得到一个例外。 (无法阅读MemoryStream)。当我尝试在CloseAndDispose()方法之后关闭并处理writer时,我得到一个例外。我应该在哪里关闭waveFileWriter

2 个答案:

答案 0 :(得分:3)

NAudio在IgnoreDisposeStream命名空间中有一个名为NAudio.Utils的辅助类。在将内存流传递到WaveFileWriter

之前,将其中的内存流包装在其中一个中
using (var writer = new WaveFileWriter(new IgnoreDisposeStream(outputStream),
                                       waveStream.WaveFormat))
{
    ...
}

答案 1 :(得分:0)

您可以将本地MemoryStream传递给WaveFileWriter并将其复制到全球版本,然后再处理:

public static void ConvertMp3ToWavStream(string inputPath)
{                           
    outputStream = new MemoryStream();
    var outputStreamLocal = new MemoryStream();
    using (...
    {        
            using (var waveFileWriter = new WaveFileWriter(outputStreamLocal, ...
            {
                ...
                outputStreamLocal.CopyTo(outputStream);
            }
    }
}