【问题标题】:Problems faced during calculating FFT of wav fileswav文件计算FFT时遇到的问题
【发布时间】:2020-08-08 20:00:17
【问题描述】:

我一直在尝试查找 .wav 文件的 FFT 转换。我的初始程序是(对于幅度 - 时间图)

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】:

第三个参数:

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.

检查docs @详情。

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

解决方案

确保您通过偶数,例如:

if n % 2 == 0:
    pass # Even 
else:
    n -= 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 2021-12-26
    • 2010-10-09
    相关资源
    最近更新 更多