在 .NET 中将 Opus (.ogg) 转换为 PCM (.wav)

Convert Opus (.ogg) to PCM (.wav) in .NET

我有一个 .ogg 文件,我需要将其转换为 .wav。我正在尝试使用 Opus.Net(使用 NAudio)但我在 OpusDecoder.Decode() 中遇到此异常:

"System.Exception: 'Decoding failed - InvalidPacket'"

这是代码:

byte[] audioBynary = File.ReadAllBytes($"{filePath}{fileOgg}");

_decoder = OpusDecoder.Create(48000, 1);
var pcmBinary = _decoder.Decode(audioBynary, audioBynary.Length, out int decodedLenght);

WaveFileWriter.CreateWaveFile($"{filePath}{fileWav}", new WaveFileReader(new MemoryStream(pcmBinary)));

这对我有用,我用 Concentus 读取了 ogg/opus 文件,将它的字节复制到 memoryStream,然后用它来创建 RawSourceWaveStream。 我可以从 RawSourceWaveStream 得到一个 ISampleProvider,这是你需要提供的 WaveFileWriter.CreateWaveFile16.

瞧瞧

        var filePath = $@"C:\Users\blabla\foo\bar\";
        var fileOgg = "testAudio.ogg";
        var fileWav = "testAudio.wav";

        using (FileStream fileIn = new FileStream($"{filePath}{fileOgg}", FileMode.Open))
        using (MemoryStream pcmStream = new MemoryStream())
        {
            OpusDecoder decoder = OpusDecoder.Create(48000, 1);
            OpusOggReadStream oggIn = new OpusOggReadStream(decoder, fileIn);
            while (oggIn.HasNextPacket)
            {
                short[] packet = oggIn.DecodeNextPacket();
                if (packet != null)
                {
                    for (int i = 0; i < packet.Length; i++)
                    {
                        var bytes = BitConverter.GetBytes(packet[i]);
                        pcmStream.Write(bytes, 0, bytes.Length);
                    }
                }
            }
            pcmStream.Position = 0;
            var wavStream = new RawSourceWaveStream(pcmStream, new WaveFormat(48000, 1));
            var sampleProvider = wavStream.ToSampleProvider(); 
            WaveFileWriter.CreateWaveFile16($"{filePath}{fileWav}", sampleProvider);