根据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)