在 memoryStream 之后处理 writer
Dispose writer after memoryStream
这是我的一段代码:
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
。当我尝试处理 writer 时,出现异常。 (无法阅读 MemoryStream
)。当我尝试在 CloseAndDispose()
方法之后关闭并处理 writer 时,出现异常。我应该在哪里关闭 waveFileWriter
?
您可以将本地 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);
}
}
}
NAudio 在 NAudio.Utils
命名空间中有一个名为 IgnoreDisposeStream
的助手 class。在将内存流传递到 WaveFileWriter
之前将其包装在其中一个中
using (var writer = new WaveFileWriter(new IgnoreDisposeStream(outputStream),
waveStream.WaveFormat))
{
...
}
这是我的一段代码:
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
。当我尝试处理 writer 时,出现异常。 (无法阅读 MemoryStream
)。当我尝试在 CloseAndDispose()
方法之后关闭并处理 writer 时,出现异常。我应该在哪里关闭 waveFileWriter
?
您可以将本地 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);
}
}
}
NAudio 在 NAudio.Utils
命名空间中有一个名为 IgnoreDisposeStream
的助手 class。在将内存流传递到 WaveFileWriter
using (var writer = new WaveFileWriter(new IgnoreDisposeStream(outputStream),
waveStream.WaveFormat))
{
...
}