简体   繁体   中英

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..

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

Another possibility would be to use librosa's spectral_centroid method. There are a lot of useful methods for audio feature extractions: Spectral Centroid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM