Skip to main content
Engineering LibreTexts

3.22: Playing Sounds

  • Page ID
    14430
  • Playing sounds that are stored in sound files is even simpler than displaying images from image files. First, you must create a pygame.mixer.Sound object (which we will call Sound objects for short) by calling the pygame.mixer.Sound() constructor function. It takes one string parameter, which is the filename of the sound file. Pygame can load WAV, MP3, or OGG files. The difference between these audio file formats is explained at http://invpy.com/formats.

    To play this sound, call the Sound object’s play() method. If you want to immediately stop the Sound object from playing call the stop() method. The stop() method has no arguments. Here is some sample code:

    soundObj = pygame.mixer.Sound('beeps.wav')
    soundObj.play()
    import time
    time.sleep(1) # wait and let the sound play for 1 second
    soundObj.stop() 
    

    You can download the beeps.wav file from invpy.com/beeps.wav.

    The program execution continues immediately after play() is called; it does not wait for the sound to finish playing before moving on to the next line of code.

    The Sound objects are good for sound effects to play when the player takes damage, slashes a sword, or collects a coin. But your games might also be better if they had background music playing regardless of what was going on in the game. Pygame can only load one music file to play in the background at a time. To load a background music file, call the pygame.mixer.music.load() function and pass it a string argument of the sound file to load. This file can be WAV, MP3, or MIDI format.

    To begin playing the loaded sound file as the background music, call the pygame.mixer.music.play(-1, 0.0) function. The -1 argument makes the background music forever loop when it reaches the end of the sound file. If you set it to an integer 0 or larger, then the music will only loop that number of times instead of looping forever. The 0.0 means to start playing the sound file from the beginning. If you pass a larger integer or float, the music will begin playing that many seconds into the sound file. For example, if you pass 13.5 for the second parameter, the sound file with begin playing at the point 13.5 seconds in from the beginning.

    To stop playing the background music immediately, call the pygame.mixer.music.stop() function. This function has no arguments.

    Here is some example code of the sound methods and functions:

    # Loading and playing a sound effect:
    soundObj = pygame.mixer.Sound('beepingsound.wav')
    soundObj.play()
    
    # Loading and playing background music:
    pygame.mixer.music.load(backgroundmusic.mp3')
    pygame.mixer.music.play(-1, 0.0)
    # ...some more of your code goes here...
    pygame.mixer.music.stop()