简体   繁体   English

使用 naudio 将 Mp3 转换为 WAV,无需写入磁盘。 (仅限流媒体)

[英]Convert Mp3 to WAV with naudio without writing on disk. (Stream only)

I want to convert mp3 files to WAV.我想将 mp3 文件转换为 WAV。 In DirectX.DirectSound the secondary buffer is supporting only WAV.在 DirectX.DirectSound 中,辅助缓冲区仅支持 WAV。 I am converting the files using naudio and this is working fine.我正在使用 naudio 转换文件,这工作正常。

using (Mp3FileReader reader = new Mp3FileReader(mp3File))
{
    WaveFileWriter.CreateWaveFile(outputFile, reader);
}

The problem is that I can't save the files on disk so I have to use them with stream.问题是我无法将文件保存在磁盘上,因此我必须将它们与流一起使用。

 Mp3FileReader mp3reader = new Mp3FileReader(filenamePathMp3);
 var stream=WaveFormatConversionStream.CreatePcmStream(mp3reader);

which throws an exception Value does not fall within the expected range.抛出异常的值不在预期范围内。 How Can I make a stream with the audio converted to WAV or Raw audio for the secondaryBuffer without writing on disk?如何在不写入磁盘的情况下将音频转换为辅助缓冲区的 WAV 或原始音频的流?

Thank you in advance,先感谢您,

WaveFileWriter can write to a Stream instead of a file so you can just pass in a MemoryStream . WaveFileWriter可以写入Stream而不是文件,因此您只需传入MemoryStream Also, Mp3FileReader.Read already returns PCM so you could read out into a byte[] and then insert that into your memory stream if you prefer.此外, Mp3FileReader.Read已经返回 PCM,因此您可以将其读出到byte[] ,然后根据需要将其插入到您的内存流中。

I've achieved to convert MP3 to WAV without writing it to the disk by using MemoryStream and WaveFileWriter.WriteWavFileToStream You can also set up sampleRate bitrate and channel using RawSourceWaveStream我已经通过使用MemoryStreamWaveFileWriter.WriteWavFileToStream实现了将 MP3 转换为 WAV 而无需将其写入磁盘您还可以使用RawSourceWaveStream设置 sampleRate 比特率和频道

public static byte[] ConvertMp3ToWav(byte[] mp3File)
{
    using (var retMs = new MemoryStream())
    using (var ms = new MemoryStream(mp3File))
    using (Mp3FileReader reader = new Mp3FileReader(ms))
    {
        var rs = new RawSourceWaveStream(reader, new WaveFormat(16000, 1));
        using (WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(rs))
        {
            WaveFileWriter.WriteWavFileToStream(retMs,pcmStream);
            return retMs.ToArray();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM