3

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

有问题的公式是:

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

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

4

2 回答 2

5

我以前从未实现过,但据我了解维基百科公式,它应该是这样的:

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
于 2014-06-24T07:20:59.920 回答
0

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

于 2019-02-22T11:39:09.883 回答