Peak generations for WaveSurfer.js using CSCore

151 Views Asked by At

I am trying to generate peaks using CSCore for WaveSurfer.js. I am essentially just trying to get peak value so it could be fed to the WaveSurfer.js element as prerendered peaks. Using CSCore as an alternative to AudioWaveForm.

Here is the code I am using:

var audioFile = CodecFactory.Instance.GetCodec("input.mp3");
var source = audioFile.ToSampleSource();

var peakMeter = new PeakMeter(source) { Interval = 40 };

var peakData = new float[source.Length / source.WaveFormat.BytesPerSample];

int read;
int i = 0;
while ((read = peakMeter.Read(peakData, i, peakData.Length - i)) > 0)
{
    i += read;
}

// Convert the peak values from dB to linear scale
for (int j = 0; j < peakData.Length; j++)
{
    decimal num = (decimal)peakData[j] * 100000;
    var e = $"{num},";
    File.AppendAllText("out.txt", e.ToString());
    //peakData[j] = (float)Math.Pow(10, peakData[j] / 20);
}

I am trying to get a CSV or and array of values. Is this correct because I am getting wildly different results. I am new to CSCore and C# as a whole so any help would be helpful.

Thanks

1

There are 1 best solutions below

1
Florian On BEST ANSWER

When using the PeakMeter you have to use its PeakCalculated event which will provide the peaks. It gets fired while reading all samples as you are already doing using the Read method. So keep calling read till it returns zero and collect the peaks using the mentioned event.