Dispose writer after memoryStream

843 Views Asked by At

This is a piece of my code:

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

This is my CloseAndDispose method, which I invoke after some manipulations:

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

The problem: after all actions I've got some memory in memory stack, which wasn't disposed. As I understand, It's my writer. When I try to dispose writer, I get an exception. (can't read MemoryStream). When I try to close and dispose writer after CloseAndDispose() method, I get an exception. Where should I close waveFileWriter?

2

There are 2 best solutions below

0
On BEST ANSWER

NAudio has a helper class called IgnoreDisposeStream in the NAudio.Utils namespace. Wrap your memory stream in one of those before passing it into the WaveFileWriter

using (var writer = new WaveFileWriter(new IgnoreDisposeStream(outputStream),
                                       waveStream.WaveFormat))
{
    ...
}
0
On

You could pass a local MemoryStream to WaveFileWriter and copy it to the global one before it's disposed:

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