Now for a bit of Python:

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

import os
from time import sleep

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
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 &')

    sleep(0.1);
$ chmod +x raspi-audio-button.py

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 raspi-audio-button.py

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.
Last updated on 2015-05-04 at 04.25.41 PM Published on 2012-07-29 at 11.58.38 AM