Python – How to implement sound in pygame?

How to implement sound in pygame?… here is a solution to the problem.

How to implement sound in pygame?

I’m having trouble writing sound effects in Space Invaders written in python. The whole game is divided into modules such as main loop, game features, settings, etc. This is part of the code that creates a new bullet and then adds it to the group. The function contains sound effects:

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 has some problems, the main one being optimization: every time the game uses a sound effect, it has to open and load a file – a problem that creates a time gap between events that generate sound and effects. How can I optimize it, such as writing a piece of code to load all the sound effects at the start of the game?

Solution

Load your sounds once in the global scope or in another module, 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()

Related Problems and Solutions