Jay
Jay

Reputation: 2282

How to convert Opus file to wav using C#?

How can I correctly convert an OPUS file to a WAV file in C#?

I attempted to use the Concentus.OggFile and NAudio.Core libraries to convert an OPUS file to WAV, but the resulting file contains only static noise instead of the expected audio.

Here's the code I tried:

using var stream = File.OpenRead("input.opus");
using var decoder = OpusCodecFactory.CreateDecoder(48000, 2);

var buffer = new Memory<byte>(new byte[8192]);
int bytesRead;
using var pcmStream = new MemoryStream();

while ((bytesRead = await stream.ReadAsync(buffer)) > 0)
{
    var chunk = buffer.Slice(0, bytesRead).ToArray();

    using var memoryChunk = new MemoryStream(chunk);
    memoryChunk.Seek(0, SeekOrigin.Begin);

    var oggStream = new OpusOggReadStream(decoder, memoryChunk);

    while (oggStream.HasNextPacket)
    {
        var packet = oggStream.DecodeNextPacket();

        if (packet == null)
        {
            continue;
        }

        for (var i = 0; i < packet.Length; i++)
        {
            var bytes = BitConverter.GetBytes(packet[i]);
            pcmStream.Write(bytes);
        }
    }
}

pcmStream.Seek(0, SeekOrigin.Begin);
var wavStream = new RawSourceWaveStream(pcmStream, new WaveFormat(48000, 2));
var sampleProvider = wavStream.ToSampleProvider();
WaveFileWriter.CreateWaveFile16("final.wav", sampleProvider);

The code generates the final.wav file, but it sounds like static, suggesting the audio might be incorrectly encoded or in the wrong format.

What am I missing? How can I properly convert an OPUS file to WAV using C#?

Upvotes: 4

Views: 45

Answers (0)

Related Questions