如何在pygame中实现声音?

时间:2018-08-19 15:29:06

标签: python pygame

我在用python写的《太空侵略者》中编写声音效果时遇到问题。整个游戏分为主循环,游戏功能,设置等模块。这是创建新项目符号并将其添加到组中的代码的一部分。函数包含声音效果:

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')`

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

1 个答案:

答案 0 :(得分:2)

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

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()