Pygame.Sound.get_num_channels inaccurate

I am using pygame + Twisted. I created a Sound wrapper class whose corresponding parts are here:

 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() 

What happens, however, is good after playing the sound .get_num_channels() returns a positive number, for example:

 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 

Why is this so?

I ask because sometimes the sound does not play at all when I talk about it, and I'm trying to figure it out. I understand that this can help with this error.

+4
source share
1 answer

In my experience, get_num_channels () counts all channels that have a sound assigned to them, even if they have finished the game.

The solution would be to go and check if all these channels are busy. You can change your _check_status method to this to take into account whether the channels are active:

 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) 

And two helper functions that may be useful to someone else experiencing this problem:

 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 
0
source

Source: https://habr.com/ru/post/1490359/


All Articles