Python Programming Tutorial: Getting Started with the Raspberry Pi

Pages
Contributors: Shawn Hymel
Favorited Favorite 30

Experiment 2: Play Sounds

Downloading audio clips and playing them on a Raspberry Pi is quite simple. We will use the command line to download a .wav file, adjust the audio, and test playing the file. Then, we'll write a Python script to play that file whenever we press a button!

Recommended Reading

  • amixer - We will be using the amixer Linux tool to adjust the volume on our Raspberry Pi
  • Pygame - Pygame is a framework that is used for making simple games in Python. Raspbian comes pre-loaded with Pygame, which means we can use it to play sounds.

Hardware Connections

Good news, everyone! We will be using the same circuit from the previous experiment.

  • Connect GPIO12 (pin 32) to the 330Ω resistor, and the resistor to the LED
  • Connect GPIO4 (pin 7) to the button
  • Make the power (3.3 V) and ground (GND) connections as shown in the Fritzing diagram

Connecting through a Pi Wedge:

Pi Wedge Fritzing diagram to connect LED and button

Connecting directly to the Raspberry Pi:

Raspberry Pi Fritzing diagram to connect LED and button

You will also need to plug an external speaker (or a set of headphones) into the Pi's headphone jack. If you are using the Hamburger Mini Speaker, make sure it is charged and turned on.

Speaker plugged into Raspberry Pi

Configure Audio

Before we write code, we need to configure the audio from the command line. Open a terminal (if you are using Raspbian with a desktop).

Note: Make sure you have selected the 3.5mm ('headphone') jack as your output audio device from the sudo rasp-config advanced options. Refer to the Configure Your Pi section to see how to do this.

From a terminal, enter the following commands:

language:bash
amixer set PCM unmute
amixer set PCM 100%

Verify that your audio is on and up by entering the command:

language:bash
amixer

At the end of the printout, you should see Mono: Playback 400 [100%] [4.00dB] [on].

Configure audio output on Raspberry Pi

Download a free sound clip (we'll go with some applause, because we're awesome):

language:bash
wget http://www.pacdv.com/sounds/people_sound_effects/applause-1.wav

Test playing this sound with:

language:bash
aplay applause-1.wav

You should hear some nice cheering and clapping out of your speaker (or headphones).

Code: Push Button, Get Sound

Depending on your version of Raspbian, you may or may not have to install the pygame package (e.g. Raspbian Lite does not come with some Python packages pre-installed). In a terminal, enter the following:

language:bash
sudo apt-get update
sudo apt-get install python3-pygame

In a new file, enter the following code:

language:python
import time
import RPi.GPIO as GPIO
from pygame import mixer

# Pins definitions
btn_pin = 4

# Set up pins
GPIO.setmode(GPIO.BCM)
GPIO.setup(btn_pin, GPIO.IN)

# Initialize pygame mixer
mixer.init()

# Remember the current and previous button states
current_state = True
prev_state = True

# Load the sounds
sound = mixer.Sound('applause-1.wav')

# If button is pushed, light up LED
try:
    while True:
        current_state = GPIO.input(btn_pin)
        if (current_state == False) and (prev_state == True):
            sound.play()
        prev_state = current_state

# When you press ctrl+c, this will be called
finally:
    GPIO.cleanup()

Save the file (e.g. applause.py), and start the program with python applause.py. Push the button, and you should hear some congratulatory sounds!

Pushing button to play sound

Troubleshooting: If you see the message "ModuleNotFoundError: No module named 'pygame'" you will need to install the pygame package by entering pip install pygame in a terminal.

Code to Note:

To play sounds, we are using the pygame package. A package in Python is a collection of modules grouped together. Lucky for us, pygame comes pre-installed with Python on Raspbian. To use it, we just need to use from pygame in our code, and we can specify which module we want to use by saying import after it. For example, we might say:

language:python
from pygame import mixer

This says that we want to import the mixer module from the pygame package. Later in our code, we can use the mixer module to create a Sound object with:

language:python
sound = mixer.Sound('applause-1.wav`)

Our downloaded file, applause-1.wav is used to create a Sound object, which we store in the sound variable. We can call the .play() method in our Sound object to start playing the .wav file.

language:python
sound.play()

Challenge: You might have noticed that if you press the button again while the sound is playing, an new sound will start that overlaps the first clip. Let's fix this! Change the code so that when you press the button while the sound is playing, the sound stops. When you press it again, the sound clip starts over again. Also, because we can, have the LED light up while the sound is playing. Hint: it might help to look at the pygame.mixer methods for determining if sound is being played (or "mixed") and how to stop a sound.