4

我正在使用 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

为什么会这样?

我问是因为有时当我告诉它时声音根本不播放,我正试图深入了解它。我认为理解这可能有助于解决该错误。

4

1 回答 1

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
于 2016-11-28T15:28:24.053 回答