With this tutorial, we are going to see how you can download audio clips and play them within a python program on a Raspberry Pi or any other hardware running a python application. For this application, you will first download wave or MP3 file, then we shall see how to adjust the audio properties of the file and test play the file from the Linux shell.
We shall them look at a Python implementation to play the Audio file as may be required. Before we start, we need to download a few libraries that we shall need
The Pygame Library is a framework that is mainly used for developing simple games in Python. In most cases, most Linux distributions including Raspbian come pre-installed with Pygame. We can therefore use this frame work to play music and sounds
In case your distribution does not have pygame pre-installed, you may install it with the commands below
pi@raspberrypi:/ $ sudo apt-get update
pi@raspberrypi:/ $ sudo apt-get install python3-pygame
With pygame installed, we will need to use another Linux tool to set our Audio properties. Amixer: allows command-line control of the mixer for the ALSA soundcard driver. We shall therefore use the amixer Linux tool to adjust the volume on our sound card.
To configure the Audio, plug your your Audio Output into your Raspberry Pi or PC. Please make sure that from your configuration (rasp-config for raspberry pi) you have the 3.5mm headphone jack selected as your primary output
With that configured, we must then apply the Audio configurations from the terminal with the following commands
pi@raspberrypi:/ $ amixer set PCM unmute
pi@raspberrypi:/ $ amixer set PCM 100%
Use the amixer command to verify that everything is running as required. You should have the result below
pi@raspberrypi: $ amixer
Simple mixer control 'Master',0
Capabilities: pvolume pswitch pswitch-joined
Playback channels: Front Left - Front Right
Limits: Playback 0 - 65536
Mono:
Front Left: Playback 99957 [153%] [on]
Front Right: Playback 99957 [153%] [on]
Simple mixer control 'Capture',0
Capabilities: cvolume cswitch cswitch-joined
Capture channels: Front Left - Front Right
Limits: Capture 0 - 65536
Front Left: Capture 99957 [153%] [on]
Front Right: Capture 99957 [153%] [on]
Now that all is set, we are ready to implement our python application. I have written a simple program to play a wave file that i a have already downloaded in my working directory. The Audio file is played in a loop with a delay of 10 seconds
import os, time
from pygame import mixer
def playSound():
# Initialize pygame mixer
mixer.init()
# Load the sounds
sound = mixer.Sound('myAudio.wav')
# play sounds
sound.play()
# wait for sound to finish playing
time.sleep(3)
if __name__ == '__main__':
while(True):
playSound()
time.sleep(10)