每个通道一次只能播放一个声音,但是一次可以播放多个通道。如果您不命名频道,pygame会选择一个未使用的频道来播放声音。默认情况下,pygame有8个频道。您可以通过创建Channel对象来指定通道。至于无限循环声音,您可以通过使用参数loops
-1播放声音来实现。您可以在http://www.pygame.org/docs/ref/mixer.html上找到这些类和方法的文档。
我还建议使用内置的模块时间,尤其是使用sleep()函数将执行暂停几秒钟的指定时间。这是因为pygame.mixer函数会在声音结束播放之前很早就返回声音,并且当您尝试在同一通道上播放第二声音时,第一声音会停止播放第二声音。因此,为确保您的“雷声”已播放完毕,最好在播放时暂停执行。我将sleep()行放在if语句之外,因为在if语句内,如果没有播放雷声,sleep()行将不会暂停执行,因此循环会非常快地循环到下一个雷声声音,输出频率远高于“偶然”。
import pygameimport randomimport timeimport var# initialize pygame.mixerpygame.mixer.init(frequency = 44100, size = -16, channels = 1, buffer = 2**12) # init() channels refers to mono vs stereo, not playback Channel object# create separate Channel objects for simultaneous playbackchannel1 = pygame.mixer.Channel(0) # argument must be intchannel2 = pygame.mixer.Channel(1)# plays loop of rain sound indefinitely until stopping playback on Channel,# interruption by another Sound on same Channel, or quitting pygamechannel1.play(var.rain_sound, loops = -1)# plays occasional thunder soundsduration = var.thunder_sound.get_length() # duration of thunder in secondswhile True: # infinite while-loop # play thunder sound if random condition met if random.randint(0,80) == 10: channel2.play(var.thunder_sound) # pause while-loop for duration of thunder time.sleep(duration)



