繁体   English   中英

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

[英]Why does pygame.mixer.Sound().play() returns None?

根据pygame文档pygame.mixer.Sound().play()应该返回一个Channel object。 它确实如此。

但有时,它似乎返回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不断返回无。

Sound.play()如果找不到播放声音的通道,则返回None ,因此您必须检查返回值。 使用while循环显然是个坏主意。

请注意,您不仅可以设置整个Channel的音量,还可以设置Sound object 的音量。 因此,您可以在尝试播放音乐之前设置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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM