【问题标题】:How to implement sound in pygame?如何在pygame中实现声音?
【发布时间】:2018-08-20 02:37:14
【问题描述】:

我在使用 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')`

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

【问题讨论】:

    标签: python pygame


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多