我正在使用pygame + Twisted。我创建了一个Sound
包装类,其相关部分在这里:
class Sound(object):
def __init__(self, sound):
self.sound = sound
self._status_task = task.LoopingCall(self._check_status)
self._status_task.start(0.05)
def _check_status(self):
chans = self.sound.get_num_channels()
if chans > 0:
logger.debug("'%s' playing on %d channels",
self.filename, chans)
def play(self):
self.sound.play()
但是,在播放完声音后,.get_num_channels()
正在返回一个正数,例如:
2013-07-08 15:13:30,502-DEBUG-engine.sound - 'sounds/foo.wav' playing on 2 channels
2013-07-08 15:13:30,503-DEBUG-engine.sound - 'sounds/bar.wav' playing on 1 channels
2013-07-08 15:13:30,546-DEBUG-engine.sound - 'sounds/foo.wav' playing on 2 channels
2013-07-08 15:13:30,558-DEBUG-engine.sound - 'sounds/bar.wav' playing on 1 channels
2013-07-08 15:13:30,602-DEBUG-engine.sound - 'sounds/foo.wav' playing on 2 channels
为什么会这样?
我问,因为当我告诉它时,有时声音根本不会播放,而我正试图找到它的底部。我认为这可能有助于解决这个问题。
答案 0 :(得分:0)
根据我的经验,get_num_channels()会计算分配给他们的声音的所有频道,即使他们已经完成播放。
解决方案是检查这些频道是否仍然“忙”。 您可以将_check_status方法更改为此方法,以考虑通道是否处于活动状态:
def _check_status(self):
chans = self.sound.get_num_channels()
if chans > 0:
logger.debug("'%s' assigned to %d channels", self.filename, chans)
active_chans = 0
for i in range(pygame.mixer.get_num_channels()):
channel = pygame.mixer.Channel(i)
if channel.get_sound() == self.sound and channel.get_busy():
active_chans += 1
logger.debug("'%s' actively playing on %d channels", self.filename, active_chans)
两个辅助函数可能对遇到此问题的其他人有所帮助:
def get_num_active_channels(sound):
"""
Returns the number of pygame.mixer.Channel that are actively playing the sound.
"""
active_channels = 0
if sound.get_num_channels() > 0:
for i in range(pygame.mixer.get_num_channels()):
channel = pygame.mixer.Channel(i)
if channel.get_sound() == sound and channel.get_busy():
active_channels += 1
return active_channels
def get_active_channel(sound):
"""
Returns the first pygame.mixer.Channel that we find that is actively playing the sound.
"""
if sound.get_num_channels() > 0:
for i in range(pygame.mixer.get_num_channels()):
channel = pygame.mixer.Channel(i)
if channel.get_sound() == sound and channel.get_busy()
return channel
return None