gpt4 book ai didi

python - pygame.Sound.get_num_channels 不准确

转载 作者:太空宇宙 更新时间:2023-11-03 12:08:32 25 4
gpt4 key购买 nike

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

为什么会这样?

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

最佳答案

根据我的经验,get_num_channels() 会计算所有已分配声音的 channel ,即使它们已完成播放也是如此。

一个解决方案是去检查这些 channel 是否仍然“繁忙”。您可以将 _check_status 方法更改为此,以考虑 channel 是否处于事件状态:

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

关于python - pygame.Sound.get_num_channels 不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17534247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com