Now for a bit of Python. There are two example files you can download to your Pi and execute with python3. The first is an script that plays a different audio bell when when each button is pressed. The second code example is a jukebox which allows one to navigate through the files, play a selected sample and stop playback using the same three buttons.

Be sure to download the following MP3 files so that you can hear the samples playing. 

  1. temple-bell.mp3
  2. temple-bell-bigger.mp3
  3. temple-bell-huge.mp3

Pulling Down the Files on the Pi

We can use wget to pull down the audio files and code directly to the Pi we are working on.

$ wget
$ wget
$ wget
$ wget
$ wget

Audio Button

# SPDX-FileCopyrightText: 2018 Mikey Sklar for Adafruit Industries
# SPDX-License-Identifier: MIT

# This script requires a Raspberry Pi 2, 3 or Zero. Circuit Python must
# be installed and it is strongly recommended that you use the latest
# release of Raspbian.

import time
import os
import board
import digitalio

print("press a button!")

button1 = digitalio.DigitalInOut(board.D23)
button1.direction = digitalio.Direction.INPUT
button1.pull = digitalio.Pull.UP

button2 = digitalio.DigitalInOut(board.D24)
button2.direction = digitalio.Direction.INPUT
button2.pull = digitalio.Pull.UP

button3 = digitalio.DigitalInOut(board.D25)
button3.direction = digitalio.Direction.INPUT
button3.pull = digitalio.Pull.UP

while True:

    # omxplayer -o local <file>
    # omxplayer -o hdmi <file>
    # omxplayer -o both <file>
    if not button1.value:
        os.system('omxplayer temple-bell.mp3 &')

    if not button2.value:
        os.system('omxplayer temple-bell-bigger.mp3 &')

    if not button3.value:
        os.system('omxplayer temple-bell-huge.mp3 &')


Running the script as indicated below should result in each button playing a different bell tone.

sudo python3 ./

Simple Jukebox

Running the as indicated below should result in each button having a different function. Audio selection, playing of the selected file and stop playing the audio file.

$ sudo python3 ./

Here, we get a list of mp3 files in the current directory, and then set up the following control scheme:

  • button #1 (GPIO 23) clicks through the list of available mp3s
  • button #2 (GPIO 24) plays the currently selected mp3
  • button #3 (GPIO 25) runs a command that kills any existing mp3 player processes, stopping whatever mp3s are playing right now

This guide was first published on Jul 29, 2012. It was last updated on Jul 12, 2024.

This page (CircuitPython Code) was last updated on Jul 12, 2024.

Text editor powered by tinymce.