2014-01-06 50 views
1

我想从窗户电话录音话筒的数据得到的音量8如何获得麦克风音量在Windows Phone 8的

microphone = Microphone.Default; 
microphone.BufferDuration = TimeSpan.FromMilliseconds(150); 
microphone.BufferReady += microphone_BufferReady; 

private void microphone_BufferReady(object sender, EventArgs e) 
{ 
     // Get buffer from microphone and add to collection 
     int size = microphone.GetSampleSizeInBytes(microphone.BufferDuration); 
     byte[] buffer = new byte[size]; 
     int bytes = microphone.GetData(buffer); 
     MicrophoneDuration += microphone.GetSampleDuration(size); 
     bufferCollection.Add(buffer); 
     //Get the volume of microphone 
     MicrophoneVolume = GetMicrophoneVolume(buffer); 
} 

/// <summary> 
/// Get the microphone volume, from 0 up to 100. 
/// 
/// The sum of data[i] square divided by the total length of the data. 
/// volume = sum(data[i] * data[i])/Length/10000 
/// </summary> 
/// <param name="data"></param> 
/// <returns></returns> 
public static double GetMicrophoneVolume(byte[] data) 
{ 
    double value = 0; 

    for (int i = 0; i < data.Length; i++) 
    { 
     value += data[i] * data[i]; 
    } 
    return ConvertTo(value/data.Length/10000); 
} 

/// <summary> 
/// x/100 = value/MaxiMicrophoneVolume/// </summary> 
/// <param name="value"></param> 
/// <returns></returns> 
private static double ConvertTo(double value) 
{ 
    if (value > MaxiMicrophoneVolume) 
     value = MaxiMicrophoneVolume; 
    if (value < 0) 
     value = 0; 

    return (100 * value)/MaxiMicrophoneVolume; 
} 

但是,在这种方法中,体积取决于每个数据的总和数据[]。开始时,当和数低时,当我们大声说话时,总和较大,但是当声音降低时,总和不会改变,因此由GetMicrophoneVolume计算的音量不会改变。

任何人都知道如何正确获得麦克风音量?
或者我的解决方案有问题吗?
此外,为什么当声音降低时数据总和不会减少?
解决问题的更好方法将不胜感激。

+0

计算你从哪里得到这个公式反正一个解决方案?另外,MaxiMicrophoneVolume的价值是什么,可能它太低了,你的计算量总是超过它。 –

+0

难道你不应该模仿xna gameloop吗? – user2737037

回答

1

谢谢你们,我终于得到了由RMS

/// <summary> 
/// Detecting volume changes, the RMS Mothod. 
/// 
/// RMS(Root mean square) 
/// </summary> 
/// <param name="data">RAW datas</param> 
/// <returns></returns> 
public static void MicrophoneVolume(byte[] data) 
{ 
    //RMS Method 
    double rms = 0; 
    ushort byte1 = 0; 
    ushort byte2 = 0; 
    short value = 0; 
    int volume = 0; 
    rms = (short)(byte1 | (byte2 << 8)); 

    for (int i = 0; i < data.Length - 1; i += 2) 
    { 
     byte1 = data[i]; 
     byte2 = data[i + 1]; 

     value = (short)(byte1 | (byte2 << 8)); 
     rms += Math.Pow(value, 2); 
    } 

    rms /= (double)(data.Length/2); 
    volume = (int)Math.Floor(Math.Sqrt(rms)); 
} 
相关问题