You can use mpg123 for basic testing but it's a little clumsy for use where you want to dynamically change the volume or have an interactive program. For more powerful audio playback we suggest using PyGame to playback a variety of audio formats (MP3 included!)

Install PyGame

Start by installing pygame support, you'll need to open up a console on your Pi with network access and run:

sudo apt-get install python3-pygame

Next, download this pygame example zip to your Pi

Run Demo

Inside the zip is an example called

This example will playback all MP3's within the script's folder. To demonstrate that you can also adjust the volume within pygame, the second argument is the volume for playback. Specify a volume to playback with a command line argument between 0.0 and 1.0

For example here is how to play at 75% volume:

python 0.75

Here's the code if you have your own mp3s!

play midi music files (also mp3 files) using pygame
tested with Python273/331 and pygame192 by vegaseat
#code modified by James DeVito from here:


import sys
import pygame as pg
import os
import time

def play_music(music_file):
    stream music with module in blocking manner
    this will stream the sound from disk while playing
    clock = pg.time.Clock()
        print("Music file {} loaded!".format(music_file))
    except pygame.error:
        print("File {} not found! {}".format(music_file, pg.get_error()))
    # If you want to fade in the audio...
    # for x in range(0,100):
    #     time.sleep(.0075)
    # # check if playback has finished

freq = 44100    # audio CD quality
bitsize = -16   # unsigned 16 bit
channels = 2    # 1 is mono, 2 is stereo
buffer = 2048   # number of samples (experiment to get right sound)
pg.mixer.init(freq, bitsize, channels, buffer)

if len(sys.argv) > 1:

        user_volume = float(sys.argv[1])
    except ValueError:
        print "Volume argument invalid. Please use a float (0.0 - 1.0)"
        raise SystemExit

    print("Playing at volume: " + str(user_volume)+ "\n")
    mp3s = []
    for file in os.listdir("."):
        if file.endswith(".mp3"):

    print mp3s

    for x in mp3s: 
        except KeyboardInterrupt:
            # if user hits Ctrl/C then exit
            # (works only in console mode)
            raise SystemExit
    print("Please specify volume as a float! (0.0 - 1.0)")

This guide was first published on Nov 21, 2017. It was last updated on Jul 24, 2024.

This page (Play Audio with PyGame) was last updated on Mar 08, 2024.

Text editor powered by tinymce.