计算wav文件FFT时遇到的问题

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

我一直在努力寻找.wav文件的FFT变换。我的初始程序是(对于AMplitude - TIme Plot)。

data_dir = 'C:/Users/asus/Desktop/Song_Test/Split/Done1.wav'

audio1, sfreq = lr.load(data_dir)
len(audio1), sfreq
Duration = len(audio1)/sfreq
print(Duration, " seconds")
time = np.arange(0, len(audio1)) / sfreq
fig, ax = plt.subplots()
ax.plot(time, audio1)
ax.set(xlabel='Time (s)', ylabel='Sound Amplitude')
plt.show()

这是我到现在为止编程的功能。

import scipy
def fft_plot(audio, sampling_rate):
    n = int(len(audio))
    T = 1 / sampling_rate
    yf = scipy.fft.fft(audio)
    print(n, T)
    xf = np.linspace(0.0, 1.0/(2.0*T), n/2.0)
    fig, ax = plt.subplot()
    ax.plot(xf, 2.0/n * np.abs(yf[:n//2]))
    plt.grid()
    plt.xlabel("Freq")
    plt.ylabel("Magnitude")
    return plt.show()

当我调用这个模块时,使用 fft_plot(audio1, sfreq)

以下是 错误 弹出

Traceback (most recent call last):
  File "C:\Users\asus\anaconda3\envs\untitled\lib\site-packages\numpy\core\function_base.py", line 117, in linspace
    num = operator.index(num)
TypeError: 'float' object cannot be interpreted as an integer

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/asus/PycharmProjects/untitled/Librosa_level2.py", line 92, in <module>
    fft_plot(audio1, sfreq)
  File "C:/Users/asus/PycharmProjects/untitled/Librosa_level2.py", line 59, in fft_plot
    xf = np.linspace(0.0, 1.0/(2.0*T), n//2.0)
  File "<__array_function__ internals>", line 6, in linspace
  File "C:\Users\asus\anaconda3\envs\untitled\lib\site-packages\numpy\core\function_base.py", line 121, in linspace
    .format(type(num)))
TypeError: object of type <class 'float'> cannot be safely interpreted as an integer.

如何解决这个浮动的问题,请大家帮帮我?

python python-3.x audio scipy fft
1个回答
2
投票

的第三个参数。

xf = np.linspace(0.0, 1.0/(2.0*T), n/2.0)

就是 n / 2.0 应该是一个整数。

num : int, optional
Number of samples to generate. Default is 50. Must be non-negative.

检查 文件 以了解详情。

您的 n 是一个整数,但当你除以 2.0 你可以得到一个分数 (实数)。在Python中 (和绝大多数其他编程语言),如果你用浮点数除以整数,你将总是得到一个浮点数。

解决方法

确保你传递的是偶数,例如:。

if n % 2 == 0:
    pass # Even 
else:
    n -= 1
© www.soinside.com 2019 - 2024. All rights reserved.