为什么pygame.mixer.Sound().play()返回None?



根据pygame文档,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(因为我使用多个线程)-没有。

有人遇到同样的问题吗?这是pygame的bug吗?

我使用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)

最新更新