如何在pygame中实现声音?



我在用python编写的Space Invaders中编程音效时遇到问题。整个游戏分为主循环、游戏功能、设置等模块。这是创建新项目符号然后将其添加到组中的代码的一部分。函数包含声音效果:

def sound_effect(sound_file):
pygame.mixer.init()
pygame.mixer.Sound(sound_file)
pygame.mixer.Sound(sound_file).play().set_volume(0.2)
def fire_bullet(si_settings, screen, ship, bullets):
"""Fire a bullet, if limit not reached yet."""
if len(bullets) < si_settings.bullets_allowed:
new_bullet = Bullet(si_settings, screen, ship)
bullets.add(new_bullet)
sound_effect('sounds/shoot.wav')`

它有一些问题,主要问题是优化:每次游戏使用音效时,它都必须打开并加载一个文件 - 这个问题在生成声音的事件和效果之间产生了时间间隔。如何优化这一点,例如编写一个代码来加载游戏开始时的所有音效?

在全局范围或其他模块中加载一次声音,然后在游戏中重复使用它们。

SHOOT_SOUND = pygame.mixer.Sound('sounds/shoot.wav')
SHOOT_SOUND.set_volume(0.2)

def fire_bullet(si_settings, screen, ship, bullets):
"""Fire a bullet, if limit not reached yet."""
if len(bullets) < si_settings.bullets_allowed:
new_bullet = Bullet(si_settings, screen, ship)
bullets.add(new_bullet)
SHOOT_SOUND.play()

最新更新