如何将 NAudio WaveStream 写入内存流?

时间:2023-03-09
本文介绍了如何将 NAudio WaveStream 写入内存流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以字节数组形式接收 mp3 数据的程序.它必须将该 mp3 数据转换为 wav 格式并将其存储在字节数据中.我正在尝试为此目的使用 NAudio.为此,我使用了以下代码.

I have a program that takes in mp3 data in a byte array. It has to convert that mp3 data into wav format and store it in a byte data. I am trying to use NAudio for this purpose. I am using the following code for this purpose.

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 将数据直接写入文件,则文件会收到正确的数据.有什么原因吗?

When I run the above code, all I receive is 0 in the byte array. But if use WaveFileWriter to write the data directly to a file, the file receives the correct data. Any reasons?

推荐答案

试试这个:

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(); 
} 

这篇关于如何将 NAudio WaveStream 写入内存流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:使用 SSH.NET 从 ByteArray/MemoryStream 上传 - 文件创建 下一篇:从流加载图像而不保持流打开

相关文章

最新文章