Now for a bit of Python:

  • Use a text editor like Nano to paste this code into a file named
  • Download or copy several mp3 files to the Pi and place them into the same directory as the script
  • Change the filenames in the code to match the files you've just copied
  • Make the file executable with chmod
#!/usr/bin/env python

import os
from time import sleep

import RPi.GPIO as GPIO

GPIO.setup(23, GPIO.IN)
GPIO.setup(24, GPIO.IN)
GPIO.setup(25, GPIO.IN)

while True:
    if (GPIO.input(23) == False):
        os.system('mpg123 -q binary-language-moisture-evaporators.mp3 &')

    if (GPIO.input(24) == False):
        os.system('mpg123 -q power-converters.mp3 &')

    if (GPIO.input(25)== False):
        os.system('mpg123 -q vader.mp3 &')

$ chmod +x

Make sure you have speakers or headphones hooked up to the 3.5mm jack, and run the Python program as an administrator using sudo:

$ sudo python

Now you should be able to trigger each mp3 by hitting the corresponding button.

A handful of things worth noticing here:

  • os.system('command') will run command just like if you typed it at the prompt.
  • The & tells the shell to run the command in the background. This way you can actually play more than one file at once.
  • The -q option to mpg123 suppresses diagnostic messages. You can remove it if you'd like to see song titles.
  • The sleep(0.1) call is necessary to avoid spawning tons of mpg123 calls from a single button press.
This guide was first published on Jul 29, 2012. It was last updated on Nov 16, 2018. This page (Code) was last updated on May 04, 2015.