Using c# to extract peaks from an opus file

38 views Asked by At

I am trying to extract peaks in a List from an Opus file.

public static List<float> ExtractPeaks2(string filePath, int samplesPerPixel)
{
    var sampleProvider = GetSampleProvider(filePath);
   // samplesPerPixel = 80000;
    float[] buffer = new float[samplesPerPixel];
    List<float> peaks = new List<float>();
    int read;

    while ((read = sampleProvider.Read(buffer, 0, buffer.Length)) > 0)
    {
    float max = 0;
    for (int index = 0; index < read; index++)
    {
        var abs = Math.Abs(buffer[index]);
        if (abs > max) max = abs;
    }
    peaks.Add(max);
}

return peaks;
}



private static ISampleProvider GetSampleProvider(string filePath)
{
    // Determine file format from file extension or header
    // and return the appropriate sample provider
    if (filePath.EndsWith(".wav"))
    {
        return new WaveFileReader(filePath).ToSampleProvider();
    }
    else if (filePath.EndsWith(".ogg"))
    {
        return new VorbisWaveReader(filePath).ToSampleProvider();
    }
    else if (filePath.EndsWith(".opus"))
    {
        return GetOpusSampleProvider(filePath);
    }
    else
    {
        throw new NotSupportedException("File format not supported.");
    }
}

private static ISampleProvider GetOpusSampleProvider(string filePath)
{
    using (var fileStream = File.OpenRead(filePath))
    {
        var opusDecoder = new OpusDecoder(48000, 2);
        var reader = new OpusOggReadStream(opusDecoder, fileStream);

        var waveFormat = WaveFormat.CreateIeeeFloatWaveFormat(48000, 2);
        var waveProvider = new BufferedWaveProvider(waveFormat)
        {
            BufferLength = 5000 * waveFormat.AverageBytesPerSecond
        };

        while (reader.HasNextPacket)
        {
            short[] pcmBuffer = reader.DecodeNextPacket();
            if (pcmBuffer != null && pcmBuffer.Length > 0)
            {
                byte[] byteBuffer = new byte[pcmBuffer.Length * 2];
                Buffer.BlockCopy(pcmBuffer, 0, byteBuffer, 0, byteBuffer.Length);

                if (waveProvider.BufferLength - waveProvider.BufferedBytes >= byteBuffer.Length)
                {
                    waveProvider.AddSamples(byteBuffer, 0, byteBuffer.Length);
                }
            }
        }

        return waveProvider.ToSampleProvider();
    }
}

I my project i need to extract peaks from Wav Ogg and Opus format files but while i can do it for wav and ogg prett straight forward im having troubles with opus. I am using Concentus.oggfile package but i am having no luck. Could somebody help me?

0

There are 0 answers