我正在用Python编写一个小音乐问答游戏(“猜笔记”),并使用PyAudio生成音频:
def gen_tone(frequency, duration=5.0, volume=0.5, fs=44100):
p = PyAudio()
# Sine wave
# samples = (np.sin(2*np.pi*np.arange(fs*duration)*frequency/fs)).astype(np.float32)
# Sawtooth wave. Can also be done with signal.sawtooth.
# samples = (np.modf(np.arange(fs*duration)*frequency/fs)[0]*2.0-1.0).astype(np.float32)
# DO NOT USE Triangle wave
# t = np.linspace(0, duration, fs*duration)
# samples = signal.sawtooth(2 * np.pi * t * frequency, width=0.5)
stream = p.open(format=paFloat32,
channels=1,
rate=fs,
output=True)
stream.write(volume * samples)
stream.stop_stream()
stream.close()
p.terminate()
正弦波听起来不太好,所以我尝试了锯齿。我想接下来测试一个三角波。上面的(注释掉)代码可以正常工作,但是当它通过我的耳塞播放时,即使是在MacBook最低的音量下,它也会通过它们产生(相当大的字面)震耳欲聋的噪音。 不要在家尝试。
情节看起来很合理:
这是怎么回事?