Python 为什么pygame.mixer.Sound().play()不返回任何值?
根据pygame.mixer.Sound().play()应该返回一个Python 为什么pygame.mixer.Sound().play()不返回任何值?,python,pygame,Python,Pygame,根据pygame.mixer.Sound().play()应该返回一个频道对象。确实如此 但有时,它似乎会返回None,因为在下一行,我得到了以下错误: NoneType has no attribute set_volume 当我试着打字时 channel = music.play(-1) channel.set_volume(0.5) 当然,错误可能会发生,因为声音很短,但错误不会来自那里(比python从一行切换到下一行的时间短5'38英寸吗?) 我还按住Ctrl+H键,查看我是否在
频道
对象。确实如此
但有时,它似乎会返回None
,因为在下一行,我得到了以下错误:
NoneType has no attribute set_volume
当我试着打字时
channel = music.play(-1)
channel.set_volume(0.5)
当然,错误可能会发生,因为声音很短,但错误不会来自那里(比python从一行切换到下一行的时间短5'38英寸吗?) 我还按住Ctrl+H键,查看我是否在某处键入了
channel=None
(因为我使用了多个线程)-什么都没有
有人有同样的问题吗?那是不是一个pygame
bug
我使用python3.8.2
,pygame2.0.1
和Windows
目前我绕过了错误,而不是像这样修复它:
channel = None
while channel is None:
channel = music.play()
channel.set_volume(0.5)
但是…它似乎没有什么帮助:游戏冻结了,因为pygame
总是不返回任何声音。Sound.play()
如果找不到播放声音的频道,则返回None
,因此必须检查返回值。使用while
循环显然是个坏主意
请注意,您不仅可以设置整个频道的音量
,还可以设置声音
对象的音量。因此,您可以在尝试播放音乐之前设置声音的音量:
music.set_volume(0.5)
music.play()
如果您想确保播放了声音
,您应该在播放之前获得一个频道
,并使用该频道
播放该声音
,类似如下:
# at the start of your game
# ensure there's always one channel that is never picked automatically
pygame.mixer.set_reserved(1)
...
# create your Sound and set the volume
music = pygame.mixer.Sound(...)
music.set_volume(0.5)
music.play()
# get a channel to play the sound
channel = pygame.mixer.find_channel(True) # should always find a channel
channel.play(music)
谢谢!它工作得很好!知道了这一点,很明显错误来自那里:错误是随机发生的,所以不是程序错误…好吧,一个问题是混音器模块的文档…不好,有时甚至只是错误。如何重复播放声音?显然channel.play(music,-1)
是。请注意,当您想播放背景音乐时,还有另一个模块:pygame.mixer.music
。