Pi Audio from Buttons

I’m doing work for a local museum. One of the projects is to setup up some audio descriptions for an exhibit. The plan is to have for example 4 buttons that would play 4 different audio files. The idea was that each of the audio files would describe a different part of the exhibit.

For my test setup I used a Raspberry Pi with 4 buttons (with resistors) that we were wired into PI GPIO pins.

There are a lot of different Raspberry Pi audio options that are available. In the past I’ve used Music Player Daemon (mpd). MPD works great, especially for playing Internet streaming radio, but I wanted to use something a little lighter. After trying a few option, I settled on the Python Simple Audio library. I found it to be light weight, easy to install and trouble free.

Simple Audio is installed by:

pip install simpleaudio

To keep things flexible I defined a couple of arrays to store the GPIO pin numbers and the audio files to play. The full code for the application is listed below.

import RPi.GPIO as GPIO
import time
import simpleaudio as sa

def play_audio(thebutton):
    homedir = '/home/pi/Music/'
    wavfiles = ['Alarm01.wav','Alarm02.wav','Alarm03.wav','free2.wav']
    wav = sa.WaveObject.from_wave_file(homedir + wavfiles[thebutton])
    print ('Playing: ',wavfiles[thebutton])
    playobj = wav.play()
    while playobj.is_playing():
    print ('Done playing')


pins = [4,17,27,22]

for thepin in pins:
    GPIO.setup(thepin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

while True:
    for index,thepin in enumerate(pins):
    if GPIO.input(thepin):
        print('Button:', index, ' Pin:',thepin)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s