微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决为什么 pygame.mixer.Sound().play() 返回 None?

根据pygame documentationpygame.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 错误吗?

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。