6

我有一个程序可以接收字节数组中的 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 将数据直接写入文件,则文件会接收到正确的数据。有什么理由吗?

4

2 回答 2

6

试试这个:

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(); 
} 
于 2012-07-16T09:45:07.520 回答
4

如果您正在写入 a MemoryStream,则需要注意WaveFileWriterMemoryStream您处理WaveFileWriter.

这是使用IgnoreDisposeStream. (另请注意,这WaveFormatConversionStream.CreatePcmStream是不必要的 -Mp3FileReader已经从 PCM 返回Read)。我也更喜欢读取试图通过整个文件的较小块。

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);
    }
}
于 2018-11-05T10:27:45.093 回答