这是我的一段代码:
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
?
答案 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);
}
}
}