Kyoshiro Kokujou
Kyoshiro Kokujou

Reputation: 1

How can i use a OpusOggReadStream as a WaveStream? (C#)

I'm currently using the NAudio player, to play music with C#. usually i use the MediaFoundationReader, but in some cases, like opus, i can't use it, it's not compatible.

so what i'm currently doing is i'm using Concentus. And with Concentus i'm decoding the whole file, load it into a separate memory stream and then use this memory stream for the wave stream.

  try
  {
      _reader = new MediaFoundationReader(trackPath);
  }
  catch
  {
      var fileIn = File.OpenRead(trackPath);
      var pcmStream = new MemoryStream();

      var decoder = OpusCodecFactory.CreateDecoder(48000, 1);
      var oggIn = new OpusOggReadStream(decoder, fileIn);

      Task.Run(() =>
      {
          while (oggIn.HasNextPacket)
          {
              var packet = oggIn.DecodeNextPacket();
              if (packet == null)
                  continue;

              foreach (var t in packet)
              {
                  var bytes = BitConverter.GetBytes(t);
                  pcmStream.Write(bytes, 0, bytes.Length);
              }
          }

          pcmStream.Position = 0;
      }).Wait();
      _reader = new RawSourceWaveStream(pcmStream, new(48000, 1));
  }

_reader is my NAudio WaveStream

now... i have some pretty big files and like one is 200MB big, and this created GIGAbytes of memory consumption and needs multiple minutes to be read, so i need better solutions for this.

my current idea is, if i skip the conversion into a memory stream i could directly use the OpusOggStream as WaveStream, therefor i'd need to convert the position in bytes into a TimeSpan... but how? my theoretical knowledge of audio codecs is 0.

also of course if you have a better idea on how i can save performance and memory consumption please let me know, too, this'd also help!

Upvotes: 0

Views: 40

Answers (0)

Related Questions