问题描述
根据pygame
documentation,pygame.mixer.sound().play()
应该返回一个Channel
对象。确实如此。
但有时,它似乎返回None
,因为下一行,我收到此错误:
nonetype has no attribute set_volume
当我尝试打字时
channel = music.play(-1)
channel.set_volume(0.5)
当然会发生错误,因为声音很短,但错误不可能来自那里(5'38" 是否比 python
需要从一行移动到下一行的时间短? )
我还Ctrl+H查看我是否在某处输入了所有代码channel = None
(因为我使用了多个线程) - 没有。
我使用 python 3.8.2
、pygame 2.0.1
和 Windows。
目前我绕过错误而不是像那样修复它:
channel = None
while channel is None:
channel = music.play()
channel.set_volume(0.5)
但是……它似乎没有多大帮助:游戏冻结了,因为 pygame
不断返回 None。
解决方法
Sound.play()
如果找不到播放声音的频道,则返回 None
,因此您必须检查返回值。使用 while
循环显然是个坏主意。
请注意,您不仅可以设置整个 Channel
的音量,还可以设置 Sound
对象的音量。因此,您可以在尝试播放之前设置 music
声音的音量:
music.set_volume(0.5)
music.play()
如果您想确保播放 Sound
,您应该先获得一个 Channel
并使用该 Channel
播放该 Sound
,如下所示:
# 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)