Python:用于.wav文件的Spectral Centroid?

问题描述 投票:2回答:2

我需要定义一个“光谱质心”函数来分析音频文件,但我无法将数学公式转换为代码。如果有人能帮助我,那就太好了,我没有想法。

有问题的公式是:

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

我已经能够通过计算信号的频谱平坦度

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

这是我如何将数学公式转换为代码的示例。我对此非常陌生,所以一个小小的举动仍然可能非常具有挑战性。我已经找到了有关几何质心的信息,但没有关于光谱的信息。

python audio centroid spectral
2个回答
3
投票

我之前从未实现过这个,但就我理解的维基百科公式而言,它应该是这样的:

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

0
投票

另一种可能性是使用librosa的spectral_centroid方法。音频特征提取有很多有用的方法:Spectral Centroid

© www.soinside.com 2019 - 2024. All rights reserved.