如何将 NAudio WaveStream 写入内存流?
Posted
技术标签:
【中文标题】如何将 NAudio WaveStream 写入内存流?【英文标题】:How to write NAudio WaveStream to a Memory Stream? 【发布时间】:2012-07-16 07:59:19 【问题描述】:我有一个程序以字节数组的形式接收 mp3 数据。它必须将该 mp3 数据转换为 wav 格式并将其存储在字节数据中。我正在尝试为此目的使用 NAudio。为此,我正在使用以下代码。
Stream inputStream = ...;
Stream outputStream = ...;
using (WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(inputStream)))
using (WaveFileWriter waveFileWriter = new WaveFileWriter(outputStream, waveStream.WaveFormat))
byte[] bytes = new byte[waveStream.Length];
waveStream.Read(bytes, 0, waveStream.Length);
waveFileWriter.WriteData(bytes, 0, bytes.Length);
waveFileWriter.Flush();
当我运行上面的代码时,我收到的只是字节数组中的 0。但是如果使用 WaveFileWriter 将数据直接写入文件,则文件会接收到正确的数据。有什么原因吗?
【问题讨论】:
你有没有试过在阅读前将位置设置为0?只是一个想法。 @ChrisGessler WaveFileWriter 不允许搜索。 不是指WaveFileWriter,WaveStream应该是可以查找的。span> 【参考方案1】:试试这个:
using (WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(inputStream)))
using (WaveFileWriter waveFileWriter = new WaveFileWriter(outputStream, waveStream.WaveFormat))
byte[] bytes = new byte[waveStream.Length];
waveStream.Position = 0;
waveStream.Read(bytes, 0, waveStream.Length);
waveFileWriter.WriteData(bytes, 0, bytes.Length);
waveFileWriter.Flush();
【讨论】:
【参考方案2】:如果您正在写信给MemoryStream
,您需要注意WaveFileWriter
将在您处理WaveFileWriter
之后处理该MemoryStream
。
这是使用IgnoreDisposeStream
的解决方法。 (另请注意 WaveFormatConversionStream.CreatePcmStream
是不必要的 - Mp3FileReader
已经从 Read
返回 PCM)。我也更喜欢读取试图通过整个文件的较小块。
var path = @"mytestFile.mp3";
var mp3ByteArray = File.ReadAllBytes(path);
var outputStream = new MemoryStream();
using (var mp3Stream = new MemoryStream(mp3ByteArray))
using (var reader = new Mp3FileReader(mp3Stream))
using (var waveFileWriter = new WaveFileWriter(new IgnoreDisposeStream(outputStream),
reader.WaveFormat))
byte[] buffer = new byte[reader.WaveFormat.AverageBytesPerSecond];
int read;
while((read = reader.Read(buffer,0, buffer.Length)) > 0)
waveFileWriter.Write(buffer, 0, read);
// outputStream has not yet been disposed so we can get the byte array from it
var wavBytes = outputStream.GetBuffer();
// or we could play it like this
outputStream.Position = 0;
using (var player = new WaveOutEvent())
using (var reader = new WaveFileReader(outputStream))
player.Init(reader);
player.Play();
while(player.PlaybackState != PlaybackState.Stopped)
Thread.Sleep(1000);
【讨论】:
以上是关于如何将 NAudio WaveStream 写入内存流?的主要内容,如果未能解决你的问题,请参考以下文章
从 WaveStream 将 2 通道样本读入数组的最简单方法