LibVLCSharp MediaPlayer AudioCallback Calculate audio level?

100 views Asked by At

I'm using LibVLCSharp MediaPlayer to shiw RSTP Media Stream - all works fine but now I need to show a audio level meter. I know that I can use AudioCallback but do not now how to calculate the level.

_mediaPlayer.SetAudioFormatCallback(AudioSetup, AudioCleanup);
_mediaPlayer?.SetAudioCallbacks(AudioCallback, PauseAudio, ResumeAudio, FlushAudio, DrainAudio);

void AudioCallback(IntPtr data, IntPtr samples, uint count, long pts)
{
...?
}
1

There are 1 answers

0
Mad Rian On

I Have done it like this:

void PlayAudioCallback(IntPtr data, IntPtr samples, uint count, long pts)
{
var buffer = new short[count]; // Buffer to hold audio samples
System.Runtime.InteropServices.Marshal.Copy(samples, buffer, 0, (int)count);

double sum = 0;
foreach (var sample in buffer)
{
    sum += sample * sample; // Square each sample and add to sum
}

double rms = Math.Sqrt(sum / count); // Calculate RMS level
double rmsNormalized = rms / 32767; // Normalize RMS value for 16-bit signed integer
double levelInDb = rmsNormalized > 0 ? 20 * Math.Log10(rmsNormalized) : minDb;

// Map dB value to 0-100 range
double level = (levelInDb - minDb) / (maxDb - minDb) * 100;
level = Math.Max(0, Math.Min(100, level)); // Clip value to 0-100 range

Dispatcher.InvokeAsync(() =>
{
    audiometer.Value = level;
});

}