在内存流之后释放编写器
本文关键字:释放 之后 内存 | 更新日期: 2023-09-27 17:59:27
这是我的代码片段:
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()
方法后关闭和处置编写器时,出现异常。我应该在哪里关闭waveFileWriter
?
NAudio 在 NAudio.Utils
命名空间中有一个名为 IgnoreDisposeStream
的帮助程序类。将您的内存流包装在其中一个中,然后再将其传递到WaveFileWriter
using (var writer = new WaveFileWriter(new IgnoreDisposeStream(outputStream),
waveStream.WaveFormat))
{
...
}
您可以将本地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);
}
}
}