Pygame混音器一次只播放一个声音
这是我的代码:
pygame.mixer.init(frequency=22050,size=-16,channels=4)
sound1 = pygame.mixer.Sound('sound1.wav')
sound2 = pygame.mixer.Sound('sound2.wav')
chan1 = pygame.mixer.find_channel()
chan2 = pygame.mixer.find_channel()
chan1.queue(sound1)
chan2.queue(sound2)
time.sleep(10)
我本以为它会同时播放 sound1
和 sound2
(因为 queue
是非阻塞的,代码会立刻进入睡眠状态)。
结果是先播放 sound1
,等 sound1
播放完了才开始播放 sound2
。
我确认这两个声道在内存中是不同的对象,所以 find_channel
并没有返回同一个声道。我是不是漏掉了什么,还是说 pygame 处理不了这个?
2 个回答
4
请查看 Pygame 文档,里面提到:
Channel.queue - 将一个声音对象排队在当前声音之后播放
所以,即使你的音轨在不同的频道上播放,如果你强制每个声音播放,它们会同时播放。
关于同时播放多个声音:
- 首先打开所有的声音文件,然后把
mixer.Sound
对象放到一个列表里。 - 接着遍历这个列表,使用
sound.play
开始播放所有声音。
这样就能强制所有声音同时播放。
另外,要确保你有足够的空频道来播放所有声音,否则某些声音可能会被打断。
在代码中可以这样写:
sound_files = [...] # your files
sounds = [pygame.mixer.Sound(f) for f in sound_files]
for s in sounds:
s.play()
你也可以为每个声音创建一个新的 Channel
,或者使用 find_channel()
来找到一个频道。
sound_files = [...] # your files
sounds = [pygame.mixer.Sound(f) for f in sound_files]
for s in sounds:
pygame.mixer.find_channel().play(s)
3
我能想到的唯一一种情况是,chan1和chan2虽然是不同的对象,但它们可能指向同一个通道。
你可以在获取通道后立即进行排队,这样你就能确保通过find_channel()得到一个不同的通道,因为find_channel()总是返回一个没有被占用的通道。
试试这个:
pygame.mixer.init(frequency=22050,size=-16,channels=4)
sound1 = pygame.mixer.Sound('sound1.wav')
sound2 = pygame.mixer.Sound('sound2.wav')
chan1 = pygame.mixer.find_channel()
chan1.queue(sound1)
chan2 = pygame.mixer.find_channel()
chan2.queue(sound2)
time.sleep(10)