How to visualize microphone sound/pressure level in Silverlight 4?
I was following this tutorial on how to make a Silverlight audio recorder. I thought it would be great to add a volume bar indicator to provide user with a feedback on what's happening. However, I can't seem to get this to work properly.
OnSamples method of AudioSink class provides raw PCM data as one of the arguments. Also, I set the AudioFrameSize property of AudioCaptureDevice to 40 (1000/40 == 25fps), so OnSamples is triggered every 40ms.
My question is how to e开发者_StackOverflowxtract the sound volume information from PCM data and display it as percentage in a progress bar [0-100]?
This is what I have so far:
double average = 0;
for (int a = 0; a < sampleData.Length; ++a)
{
average += Math.Abs(sampleData[a]);
}
average /= sampleData.Length;
double volume = 20 * Math.Log10(average);
Value of the progress bar is then set to volume:
progressBar.Value = volume;
My code doesn't work, apparently, since the volume value is almost always at the same level.
Any help is appreciated!
try this...this is for (8000,8,1) if you are using 2 channels replace "index+=1" with "index+=2"
for (int index = 0; index < sampleData.Length; index += 1)
{
short sample = (short)((sampleData[index + 1] << 8) | sampleData[index + 0]);
//short sample = (short)(sampleData[index + 0]);
float sample32 = sample / 32768f;
float maxValue = 0;
float minValue = 0;
maxValue = Math.Max(maxValue, sample32);
minValue = Math.Min(minValue, sample32);
float lastPeak = Math.Max(maxValue, Math.Abs(minValue));
this.MicLevel = (100 - (lastPeak * 100)) * 10;
//System.Diagnostics.Debug.WriteLine("Mic Level: " + this.MicLevel.ToString());
}
精彩评论