Evan_Balster

Simple Spectral Centroid Algorithm

Feb 1st, 2016
325
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.97 KB | None | 0 0
  1. #define PI 3.14159265359
  2.  
  3. /*
  4.     Compute the spectral centroid in hertz for an input signal of finite length.
  5.         This is a very simplistic implementation which can be improved upon.
  6.  
  7.         input        -- the input signal buffer.
  8.         sample_count -- the size of the input signal buffer.
  9.         sample_rate  -- the sampling rate in hertz.
  10. */
  11.  
  12. double spectral_centroid(const double *input, int sample_count, double sample_rate)
  13. {
  14.     double aPowerSum = 0.0, bPowerSum = 0.0;
  15.  
  16.     for (int i = 1; i < sample_count; ++i)
  17.     {
  18.         double a = input[i], b = input[i] - input[i-1];
  19.         aPowerSum += a*a;
  20.         bPowerSum += b*b;
  21.     }
  22.  
  23.     return sqrt(bPowerSum / aPowerSum) * sample_rate / (2.0*PI);
  24. }
  25.  
  26. //To the extent possible under law, Evan D. Balster has waived all copyright and related or neighboring rights to this Spectral Centroid Algorithm.  See: https://creativecommons.org/publicdomain/zero/1.0/
  27.  
  28. //This code was updated on 2016-02-09 to correct several math errors pointed out by Oriol Romani Picas.
Add Comment
Please, Sign In to add comment