如何在Pygame中为通道分配声音?
我正在尝试在Pygame中同时播放多种声音。我有背景音乐,我想连续播放雨声并播放雷声。
我尝试了以下方法,但是在播放雷声时雨声会停止。我尝试使用通道,但是我不知道如何选择要播放声音的通道,或者是否可以一次播放两个通道。
var.rain_sound.play()
if random.randint(0,80) == 10:
thunder = var.thunder_sound
thunder.play()
感谢您的帮助
-
每个通道一次只能播放一个声音,但是一次可以播放多个通道。如果您不命名频道,pygame会选择一个未使用的频道来播放声音。默认情况下,pygame有8个频道。您可以通过创建Channel对象来指定通道。至于无限循环声音,您可以通过使用参数loops
-1播放声音来实现。您可以在http://www.pygame.org/docs/ref/mixer.html上找到这些类和方法的文档。
我还建议使用内置的模块时间,尤其是使用sleep()函数将执行暂停几秒钟的指定时间。这是因为pygame.mixer函数会在声音结束播放之前很早就返回声音,并且当您尝试在同一通道上播放第二声音时,第一声音会停止播放第二声音。因此,为确保您的“雷声”已播放完毕,最好在播放时暂停执行。我将sleep()行放在if语句之外,因为在if语句内,如果没有播放雷声,sleep()行将不会暂停执行,因此循环会非常快地循环到下一个雷声声音,输出频率远高于“偶然”。import pygame import random import time import var # initialize pygame.mixer pygame.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 playback channel1 = pygame.mixer.Channel(0) # argument must be int channel2 = pygame.mixer.Channel(1) # plays loop of rain sound indefinitely until stopping playback on Channel, # interruption by another Sound on same Channel, or quitting pygame channel1.play(var.rain_sound, loops = -1) # plays occasional thunder sounds duration = var.thunder_sound.get_length() # duration of thunder in seconds while 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)