对 simpleaudio 项目使用 numpy.linspace() 方法,当我将持续时间更改为浮点数时出现类型错误。我该如何解决这个问题?

Using numpy.linspace() method for a simpleaudio project, I get a typeError when I change the duration to a float. How do I work around this problem?

"""Here is the exact code from the simpleaudio docs which produces the error TypeError: object of type cannot be safely interpreted as an integer. The problem is T = 0.25. Everything works fine as long as T is an integer, however I require the ability to work with T as a decimal. """

import numpy as np
import simpleaudio as sa

# calculate note frequencies
A_freq = 440
Csh_freq = A_freq * 2 ** (4 / 12)
E_freq = A_freq * 2 ** (7 / 12)

# get timesteps for each sample, T is note duration in seconds
sample_rate = 44100
T = 0.25
t = np.linspace(0, T, T * sample_rate, False)

# generate sine wave notes
A_note = np.sin(A_freq * t * 2 * np.pi)
Csh_note = np.sin(Csh_freq * t * 2 * np.pi)
E_note = np.sin(E_freq * t * 2 * np.pi)

# concatenate notes
audio = np.hstack((A_note, Csh_note, E_note))
# normalize to 16-bit range
audio *= 32767 / np.max(np.abs(audio))
# convert to 16-bit data
audio = audio.astype(np.int16)

# start playback
play_obj = sa.play_buffer(audio, 1, 2, sample_rate)

# wait for playback to finish before exiting
play_obj.wait_done()

问题实际上并不是来自 T 本身,而是来自 T * sample_ratelinspace 将其第一个和第二个参数之间的 space 分为 n + 1 部分(或等效地, n 点),其中 n 是其第三个参数。尽管 T * sample_rate 在数学上是一个整数,但它是 float 您计算它的方式。因此,为了让您的代码正常工作,您只需将其转换为 int:

sample_rate = 44100
T = 0.25
t = np.linspace(0, T, int(T * sample_rate), False)