numpy数组的光谱质心

时间:2019-01-04 02:43:27

标签: python arrays numpy scipy wav

我有一个.wav文件(在此示例中为“ piano2.wav”)。

我想在python中找到谱的质心。

使用此处另一篇文章中的代码,我有此功能:

import numpy as np
from scipy.io.wavfile import read

def spectral_centroid(x, samplerate=44100):
    magnitudes = np.abs(np.fft.rfft(x))
    length = len(x)
    freqs = np.abs(np.fft.fftfreq(length, 1.0/samplerate)[:length//2+1])
    return np.sum(magnitudes*freqs) / np.sum(magnitudes) 

我使用scipy.io.wavfile.read将wav文件读取到numpy数组中,然后尝试将其输入上述函数中

a=read("piano2.wav")
print("Spectral centroid is " + spectral_centroid(a[1]))

这是我得到的错误

  File "test.py", line 20, in <module>
    print("Spectral centroid is " + spectral_centroid(a[1]))
  File "test.py", line 8, in spectral_centroid
    return np.sum(magnitudes*freqs) / np.sum(magnitudes) 
ValueError: operands could not be broadcast together with shapes (302712,2) (151357,)

1 个答案:

答案 0 :(得分:1)

您正在尝试将不同形状的数组(magnitudesfreqs)相乘:

a = np.arange(10)
b = np.arange(5)
print(a*b)
  

ValueError:操作数不能与形状(10,)(5,)一起广播

这可能会帮助:

def spectral_centroid(x, samplerate=44100):
    magnitudes = np.abs(np.fft.rfft(x))
    length = len(x)
    freqs = np.abs(np.fft.fftfreq(length, 1.0/samplerate)[:length//2+1])
    magnitudes = magnitudes[:length//2+1]
    return np.sum(magnitudes*freqs) / np.sum(magnitudes)