Search code examples
pythonaudiocentroid

Python: Spectral Centroid for a .wav file?


I need do define a "spectral centroid" function that will analyze an audio file but I'm not able to convert the mathematical formula into code. If anybody could help me it would be great, I'm out of ideas.

the formula in question is:

http://en.wikipedia.org/wiki/Spectral_centroid

I've been able to calculate the spectral flatness of a signal by

def spectral_flatness(x): 
    X_f = fft(x) 
    N = len(X_f) 
    magnitude = abs(X_f[:N/2]) 
    sf = geom_mean(magnitude) / aritm_mean(magnitude) 
    return sf

This is an example of how i was able to convert a mathematical formula into code. I'm very new to this so a small move can still be quite challenging. I've found info on geometrical centroids but none on spectral ones..


Solution

  • I have never implemented this before but as far as I understand the Wikipedia formula, it should be something like this:

    import numpy as np
    
    def spectral_centroid(x, samplerate=44100):
        magnitudes = np.abs(np.fft.rfft(x)) # magnitudes of positive frequencies
        length = len(x)
        freqs = np.abs(np.fft.fftfreq(length, 1.0/samplerate)[:length//2+1]) # positive frequencies
        return np.sum(magnitudes*freqs) / np.sum(magnitudes) # return weighted mean