如何在pcm流中找到音频功率(db)(c#)

时间:2011-06-12 07:46:09

标签: c# .net audio audio-streaming pcm

我有一个pcm 16位流,我需要知道音频何时通过特定的电源。 我是否需要fft,或者我能以更简单的方式知道它?

由于

1 个答案:

答案 0 :(得分:0)

我认为你需要FFT。

FFT中提供以下方法。 (一般)

  /* Calculate normal power

   NumSamples : Number of sample 
   pReal : Real coefficient buffer 
   pImag : Imaginary coefficient buffer 
   pAmpl :  Working buffer to hold amplitude Xps(m) = | X(m)^2 | = Xreal(m)^2  + Ximag(m)^2</param>
    */ 
    public static void NormalPower(UInt32 NumSamples, Double[] pReal, Double[] pImag, Double[] pAmpl)
    {
        // Calculate amplitude values in the buffer provided
        for (UInt32 i = 0; i < NumSamples; i++)
        {
            pAmpl[i] = pReal[i]*pReal[i] + pImag[i]*pImag[i];
        }
    }

    /* Find Peak frequency in Hz

    NumSamples : Number of samples 
    pAmpl : Current amplitude 
    samplingRate : Sampling rate in samples/second (Hz) 
    index : Frequency index 
    <returns>Peak frequency in Hz</returns>
     * */
    public static Double PeakFrequency(UInt32 NumSamples, Double[] pAmpl, Double samplingRate, ref UInt32 index)
    {
        UInt32 N = NumSamples >> 1;   // number of positive frequencies. (numSamples/2)
        double maxAmpl = -1.0;
        double peakFreq = -1.0;
        index = 0;

        for (UInt32 i = 0; i < N; i++)
        {
            if ( pAmpl[i] > maxAmpl )
            {
                maxAmpl = (double)pAmpl[i];
                index = i;
                peakFreq = (double)(i);
            }
        }
      return samplingRate * peakFreq / (double)(NumSamples);
    }

你可以像这样使用它们:

   FFT.Compute(_numSamples, RealIn, null, RealOut, ImagOut, false);
               FFT.NormalPower(_numSamples / 2, RealOut, ImagOut, AmplOut);

               double maxAmpl = (32767.0 * 32767.0);  //Max power used for 16 bit audio
               int centerFreq = (Rate / 2);
               for (int i = 0; i < NUM_FREQUENCY; ++i)
               {
                   if (METER_FREQUENCY[i] > centerFreq)
                       _meterData[i] = 0;
                   else
                   {
                       var indice = (int)(METER_FREQUENCY[i] * _numSamples / Rate);
                       var metervalue = (int)(20.0 * Math.Log10(AmplOut[indice] / maxAmpl));
                       _meterData[i] = metervalue;
                   }
               }

注意:要获得以dB为单位的声音强度,请使用以下公式:

level = 20 Log(P2 / P1)

P1 =最大功率

P2 =当前功率