python-3.x - 如何在pygame中以同一毫秒播放多个声音文件?
问题描述
我正在尝试同时播放 6 个声音文件 (aiff),每个 5 mb,或者它们最接近相同的毫秒数。但是我的代码导致一团糟:确实同时播放了一些声音,但有些没有。您可以听到在不同时间播放的 3 种声音。所以......就像6个声音被分成3组2个声音,导致这3个声音在不同的时间。这一定是个线索...
这些文件存储在 ram 内存中(因为我使用的是加载到 ram 中的实时 lubuntu 图像),所以它非常快,我认为它没有滞后问题。即使因为当我加载存储在 pendrive 中的声音时,结果听起来完全一样。所以这里绝对不是问题。
import pygame as pg
pg.init()
pg.mixer.set_num_channels(50)
pg.mixer.Channel(1).play(pg.mixer.Sound('/home/lubuntu/Piano.pp.B2.aiff'))
pg.mixer.Channel(2).play(pg.mixer.Sound('/home/lubuntu/Piano.pp.A3.aiff'))
pg.mixer.Channel(3).play(pg.mixer.Sound('/home/lubuntu/Piano.pp.A4.aiff'))
pg.mixer.Channel(4).play(pg.mixer.Sound('/home/lubuntu/Piano.pp.A5.aiff'))
pg.mixer.Channel(5).play(pg.mixer.Sound('/home/lubuntu/Piano.pp.A6.aiff'))
pg.mixer.Channel(6).play(pg.mixer.Sound('/home/lubuntu/Piano.pp.A1.aiff'))
解决方案
通过从以下位置加载 6 个声音文件进行测试:
http://theremin.music.uiowa.edu/MISpiano.html
我怀疑调用每个 play() 然后调用它自己的 load() 会创建你的交错效果,因为 play2 在 play1 已经播放之前甚至无法考虑开始加载它的声音。
import pygame as pg
import time
pg.init()
pg.mixer.set_num_channels(50)
foo = [
pg.mixer.Sound("Piano.pp.A1.aiff"),
##pg.mixer.Sound("Piano.pp.A2.aiff"),
pg.mixer.Sound("Piano.pp.A3.aiff"),
pg.mixer.Sound("Piano.pp.A4.aiff"),
pg.mixer.Sound("Piano.pp.A5.aiff"),
pg.mixer.Sound("Piano.pp.A5.aiff"),
pg.mixer.Sound("Piano.pp.B2.aiff"),
]
for i,x in enumerate(foo):
pg.mixer.Channel(i+1).play(x)
time.sleep(10) ## so you can hear something rather than having the app just quit
我认为当我大胆地打开这 6 个文件并将它们一起播放时,这或多或少会产生我听到的声音。只是提醒一下,他们似乎大多是沉默的。