对于我的大学项目,我想写一点,我们称之为"仪器"。 所以只要按下指定按钮,我就想播放声音(正弦波)。
到目前为止我所拥有的是:
#create a sine array with frequency, samplerate and duration:
def sine(freq, samplerate, duration):
duration = duration * samplerate
wave = [math.sin(2.0 * math.pi * freq * t / samplerate) for t in range(0, duration)]
return numpy.array(wave)
# this is the point int the main loop where the sound has to be played
if key[pygame.K_p]:
pygame.sndarray.make_sound(sine(440, 44100, duration).play()
问题在于,如果我按下按钮,它会在我设置的时间内播放并在每次循环识别出我按下按钮时覆盖它。
我认为它应该能够获得当前时间和释放按钮的时间,但不知道如何让它实现它。
也许你有一些方法可供我使用。
答案 0 :(得分:0)
你可以让播放声音的if语句只在每个“持续时间”秒内处理,这样最后一个声音文件就会在它开始下一个声音文件时结束。
你也可以尝试使用pygame.mixer.sound这样你可以播放任何声音。然后使用.play方法,你可以让它播放10000次,并在释放按钮时调用stop。
我建议如何测试释放按下按钮是否保持另一个变量中按钮的最后状态。离。
pWasPressed = pygame.K_p
然后让你的if语句
if(pWasPressed = false和pygame.K_p):
这只会在您第一次按下该键时触发,并且不会在每次循环运行时继续运行if语句。
希望有所帮助。答案 1 :(得分:0)
尝试使用if语句检查声音当前是否正在播放。
# check the mixer is not engaged when the key is down
if key[pygame.K_p] and (not pygame.mixer.get_busy() ):
<your sound>.play()
# check if the mixer is engaged when the key is up
elif not key[pygame.K_p] and pygame.mixer.get_busy():
<your sound>.stop()
为此,您可能希望在开头创建声音并将其存储在变量中,否则将很难引用它以便稍后停止。