0

"""这里是来自 simpleaudio 文档的确切代码,它会产生错误 TypeError: object of type can not besecurelyinterpreted as an integer. 问题是 T = 0.25。只要 T 是整数,一切都可以正常工作,但是我需要将 T 用作小数的能力。"""

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()
4

1 回答 1

1

问题实际上并不是来自T它本身,而是来自T * sample_rate. linspace将它的第一个和第二个参数之间的空间划分为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)
于 2020-05-11T21:24:36.187 回答