Pygame设置超过2个声音通道时第三通道报错如何解决
问题原因
你在代码前半段将sfx定义为pygame.mixer.Channel(2)的通道对象,但是在代码后半段又将同名的sfx变量重新赋值为存储音效文件的字典,原来的通道对象被完全覆盖。后续调用sfx.play()的时候实际操作的是存储音效的字典对象,自然会触发'dict' object has no attribute 'play'的报错,前两个变量music、ambience没有被重新赋值,所以运行正常。
解决方案
- 方案1:修改音效字典的变量名,避免和通道变量重名,比如把存储音效的字典改名为
sfx_sounds,后续调用音效的时候从这个字典里取,播放时调用sfx通道的play方法,示例代码:
# 原sfx通道定义保留 sfx = pygame.mixer.Channel(2) # 把原来的sfx字典改名 sfx_sounds = { 'ship_move' : get_sound('effects', 'ship_move_01.wav'), 'select_destination' : get_sound('effects', 'select_destination_01.wav'), } # 播放示例 sfx.play(sfx_sounds['ship_move'])
- 方案2:修改通道的变量名,比如把音效通道改名为
sfx_channel,后续播放时调用sfx_channel的play方法:
# 通道改名 sfx_channel = pygame.mixer.Channel(2) # 音效字典保留原名sfx sfx = { 'ship_move' : get_sound('effects', 'ship_move_01.wav'), 'select_destination' : get_sound('effects', 'select_destination_01.wav'), } # 播放示例 sfx_channel.play(sfx['ship_move'])
附加优化建议
你当前get_sound函数里的路径拼接用了硬编码的反斜杠,跨平台运行会出错,建议统一用os.path.join处理所有路径拼接:
def get_sound(folder, sound): return pygame.mixer.Sound(os.path.join(os.path.dirname(__file__), 'sounds', folder, sound))
内容的提问来源于stack exchange,提问作者Joel S
相关产品推荐
相关产品推荐

