Skip to content
Related Articles
Open in App
Not now

Related Articles

Python | Playing audio file in Pygame

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 27 Feb, 2020
Improve Article
Save Article

Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the best modules for doing so.

Note: For more information, refer to Introduction to pygame

In order to play music/audio files in pygame, pygame.mixer is used (pygame module for loading and playing sounds). This module contains classes for loading Sound objects and controlling playback. There are basically four steps in order to do so:

  • Starting the mixer
  • Loading the song."song.mp3")
  • Setting the volume.
  • Start playing the song.

Below is the implementation.

from pygame import mixer
# Starting the mixer
# Loading the song"song.mp3")
# Setting the volume
# Start playing the song
# infinite loop
while True:
    print("Press 'p' to pause, 'r' to resume")
    print("Press 'e' to exit the program")
    query = input("  ")
    if query == 'p':
        # Pausing the music     
    elif query == 'r':
        # Resuming the music
    elif query == 'e':
        # Stop the mixer



This code will also play the “song.mp3” file.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!