Playing Music in Pygame using Python

In this tutorial, we are going to see how to insert music or sound into our pygame file using Python. We can also play music in Python using Pygame. Before starting let us ensure where would this kind of concept is useful. when we create a game in Python using pygame that involves some characters where the character crashes or hit with bullets we would like to generate sound and to incorporate background music during the game this module is helpful.

Before we can start using our sound and music files we need to load them.

The syntax for loading music files and sound files is as follows.


The pygame can load WAV, MP3, OGG  these are extensions of the sound file and take them as input to pygame.mixer.

Working with Sound and Music Files using pygame.mixer in Python

To incorporate sound files we use pygame.mixer.Sound(). This is assigned with an object as follows


In the above example, we used bullet sound where

  •  is used to play the sound.
  • soun_obj.stop()  is used to stop the sound.

To incorporate music files we use This can be used directly without creating an object."helicopter.mp3")

In the above example, we used helicopter sound as background music where

  •  is used to start the background music.
  •  is used to stop the background music.

It will play music for 4 seconds only. Later, it will stop likewise you can specify how many numbers of seconds you want to play the music. By default, it is set to zero (0). we can play music as long as the pygame window is opened by using this statement

The following code will represent the working of sound and music files.

import pygame
import sys
pygame.display.set_caption("sound demo")"ringtone.mp3")
while True:
      for eve in pygame.event.get():
            if eve.type==pygame.QUIT:


In the above code, we will get the blank screen with background music ringtone and bullet sound playing.we can stop the music by including stop() as mentioned above.

We can play more than one music each time by using a random module that helps us to play random music. The code is as follows

import random

It helps us to load different background music each time from the list we have created.

NOTE: The sound files and the Python file must be in the same folder

Music Files: (We can play both .wav and .mp3 file)


Leave a Reply

Your email address will not be published. Required fields are marked *