python - numpy 数组的谱质心

标签 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,)

最佳答案

您正在尝试将不同形状的数组(幅度频率)相乘:

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) 

关于python - numpy 数组的谱质心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54032515/

相关文章:

c - 结构中数组和结构数组的动态内存分配

python - 升级到 scikit 0.15 时导入错误,numpy 警告

python - pathlib Path.rglob 在 Windows 中的长文件路径上失败

python - 计算一行在矩阵中出现的次数(numpy)

python - 通过 Python 和 Google SMTP 服务器发送电子邮件

python - 无法使用请求从网页获取特定项目

javascript - 如何在 javascript 中制作背景数组

PHP通过值删除数组索引

python - 随机更改 numpy 数组值

python - 如何使 NumPy 数组属性的元素可设置?