How to play an audio file in Pygame

Pygame is a set of Python modules designed to create games and multimedia programs.

In this shot, we will go through how to play an audio file in Pygame.

Pygame comes with a module called mixer, with which we will play an audio file.

Pre-requisites

  • Download and install the latest Python version.
  • Install the Pygame module with pip.
pip install pygame
  • Download any audio file ending with the .mp3 extension.

Implementation

Steps

  • Import the mixer module from the pygame module.
  • Instantiate mixer.
  • Load the audio file.
  • Set desired volume.
  • Play the music.

The above steps are enough to play the audio, but we can pause, resume, and stop the music playback.

The following code snippet will play the audio using mixer in Pygame.

  • Line 1: Import mixer from pygame.
  • Line 4: Instantiate mixer with mixer.init().
  • Line 7: Load the audio file by providing the path.
  • Line 12: Set your desired volume.
  • Line 15: Play the music.
  • Line 18: Use while True to run the loop infinitely. We will stop this loop when the user stops the music.
    • Line 20 to 22: Instructions to be displayed while audio is playing, so that user can pause, resume, and stop the music.
    • Line 25: Take user input
    • Line 27 to 42: Use if-else condition to check user-entered input.
from pygame import mixer
#Instantiate mixer
mixer.init()
#Load audio file
mixer.music.load('song.mp3')
print("music started playing....")
#Set preferred volume
mixer.music.set_volume(0.2)
#Play the music
mixer.music.play()
#Infinite loop
while True:
print("------------------------------------------------------------------------------------")
print("Press 'p' to pause the music")
print("Press 'r' to resume the music")
print("Press 'e' to exit the program")
#take user input
userInput = input(" ")
if userInput == 'p':
# Pause the music
mixer.music.pause()
print("music is paused....")
elif userInput == 'r':
# Resume the music
mixer.music.unpause()
print("music is resumed....")
elif userInput == 'e':
# Stop the music playback
mixer.music.stop()
print("music is stopped....")
break

Output

widget

Free Resources