2011-08-05 62 views
2

我正在關注如何製作Silverlight錄音機的this tutorial。我認爲添加一個音量欄指示器以向用戶提供關於發生的事情的反饋會很棒。但是,我似乎無法讓這個工作正常。如何在Silverlight 4中可視化麥克風聲音/壓力級別?

OnSamples AudioSink類的方法提供原始PCM數據作爲參數之一。另外,我將AudioCaptureDeviceAudioFrameSize屬性設置爲40(1000/40 == 25fps),因此OnSamples每40ms觸發一次。

我的問題是如何從PCM數據中提取音量信息並在進度條[0-100]中將其顯示爲百分比?


這是我到目前爲止有:進度條的

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); 

值會被設置爲音量:

progressBar.Value = volume; 

我的代碼不能正常工作,很顯然,因爲音量值幾乎總是處於相同的水平。

任何幫助表示讚賞!

回答

2

試試這個......這是(8000,8,1),如果您使用的是2個通道取代「指數+ = 1」與「指數+ = 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()); 
      }