ca.ribou
ca.ribou

Reputation: 39

How to implement sound in pygame?

I have a problem with programming the sound effects in Space Invaders wrote in python. Entire game is divided into modules like the main loop, game functions, settings etc. This is a part of the code that create new bullet and then adds it into the group. Function contains the sound effect:

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

It have some issues, the main problem is the optimization: every time the game use an sound effect, it have to open and load a file - this issue create time gap between event generating the sound and the effect. How can I optimize this and for example write a code that load all sound effects at the start of the game?

Upvotes: 3

Views: 2149

Answers (1)

skrx
skrx

Reputation: 20438

Load your sounds once in the global scope or in another module and then reuse them in your game.

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

Upvotes: 3

Related Questions