numpy 数组的光谱质心
spectral centroid of numpy array
我有一个 .wav
文件(在本例中称为 "piano2.wav")。
我想找到 python 中的光谱质心。
使用这里另一个 post 的代码,我有这个功能:
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,)
您正在尝试乘以不同形状的数组(magnitudes
和 freqs
):
a = np.arange(10)
b = np.arange(5)
print(a*b)
ValueError: operands could not be broadcast together with shapes (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)
我有一个 .wav
文件(在本例中称为 "piano2.wav")。
我想找到 python 中的光谱质心。
使用这里另一个 post 的代码,我有这个功能:
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,)
您正在尝试乘以不同形状的数组(magnitudes
和 freqs
):
a = np.arange(10)
b = np.arange(5)
print(a*b)
ValueError: operands could not be broadcast together with shapes (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)