Attach a powered speaker such as the one shown in Figure 15-1.
Having attached the speaker to the audiovisual socket, you will also need to configure the Raspberry Pi to play through the audiovisual jack, not HDMI, using Recipe 15.2.
An alternative to using a general-purpose speaker like the one shown in Figure 15-1 is to use a speaker kit designed specifically for the Raspberry Pi, such as the MonkMakes Speaker Kit for Raspberry Pi, shown in Figure 15-2.
This speaker is connected using the audio lead supplied with the kit, and the speaker uses the Raspberry Pi’s 5V power supply, connected using the female-to-female leads.
Raspbian comes with a handy program to test that your speaker is working. Type the following command in the Terminal:
$ speaker-test -t wav -c 2 speaker-test 1.1.3 Playback device is default Stream parameters are 48000Hz, S16_LE, 2 channels WAV file(s) Rate set to 48000Hz (requested 48000Hz) Buffer size range from 256 to 32768 Period size range from 256 to 32768 Using max buffer size 32768 Periods = 4 was set period_size = 8192 was set buffer_size = 32768 0 - Front Left 1 - Front Right Time per period = 2.411811 0 - Front Left 1 - Front Right
When you run this command, you will hear a voice saying front left, front right, and so on. This is designed to test a stereo audio setup.
As well as connecting amplified loudspeakers of various types, you can also directly connect a pair of headphones to a Raspberry Pi’s audio socket.
By default, a Raspberry Pi’s output is set to be via the HDMI cable. So if your Pi is connected to a TV or a monitor with built-in speakers, all you need to do to hear sounds from your Raspberry Pi is to turn up the volume on your TV or monitor.
However, if you are using the Raspberry Pi without a monitor, or your monitor does not have speakers, you can follow this recipe.
To specify where sound is output, see Recipe 15.2.
To play a test sound, see Recipe 15.4.
To pair your Raspberry Pi with a Bluetooth speaker, see Recipe 1.18.
For more information on the Speaker Kit for Raspberry Pi, see https://oreil.ly/Q73vu.
The simplest way to set the audio output is to use the selector available when you right-click the Speaker icon in the upper-right corner of your desktop (Figure 15-3).
Note that the entry Comiso M20 in Figure 15-3 is for a Bluetooth speaker that has already been paired with the Raspberry Pi (see Recipe 1.18).
If you are running your Raspberry Pi headless (without a monitor), you can still control where the sound is output on your Raspberry Pi using the raspi-config
command-line utility.
Open a Terminal session and enter the following command:
$ sudo raspi-config
Then select the option Advanced, followed by Audio. You can then select the option you want, as shown in Figure 15-4.
To learn about connecting a speaker to your Raspberry Pi, see Recipe 15.1.
For more sound input and output options, you can use the Audio Device Settings tool; see Recipe 15.5.
Use the built-in OMXPlayer software from the command line. To try this out, locate the file called school_bell.mp3 in this book’s downloads in the python directory. You can play this license-free sound using the following command:
$
omxplayer -olocal
/home/pi/raspberrypi_cookbook_ed3/python/school_bell.mp3
This will play the sound file through the headphone jack. If you would rather play the sound through the HDMI connection, you can use -o hdmi
instead of -o local
.
The OMXPlayer will play most types of sound files, including MP3, WAV, AIFF, AAC, and OGG. However, if you want to play only uncompressed WAV files, you can also use the lighter-weight aplay
command:
$
aplay school_bell.wav
If you need to play the sound from a Python program, you can use the Python subprocess
module (ch_15_play_sound.py), as shown here:
import
subprocess
sound_file
=
'/home/pi/raspberrypi_cookbook_ed3/python/school_bell.mp3'
sound_out
=
'local'
subprocess
.
run
([
'omxplayer'
,
'-o'
,
sound_out
,
sound_file
])
As with all the program examples in this book, you can also download this program (see Recipe 3.22).
You can also play sounds using the pygame
library (ch_15_play_sound_pygame.py), as illustrated here:
import
pygame
sound_file
=
'/home/pi/raspberrypi_cookbook_ed3/python/school_bell.wav'
pygame
.
mixer
.
init
()
pygame
.
mixer
.
music
.
load
(
sound_file
)
pygame
.
mixer
.
music
.
play
()
while
pygame
.
mixer
.
music
.
get_busy
()
==
True
:
continue
The sound file must be either an OGG file or an uncompressed WAV file. I found that the sound would play only through the HDMI channel.
To play sounds directly from the command line, see Recipe 15.3.
You also can use pygame
for intercepting keypresses (Recipe 12.11) and mouse movements (Recipe 12.12).
Use a USB microphone like the one shown in Figure 15-5, or something a bit more substantial and of better quality.
These devices come in various shapes and sizes. Some fit directly into the USB socket; others have a USB lead attached to them; and some are part of a headset.
Having plugged in your USB microphone, check that Raspbian is aware of it by running this command, which lists available devices from which you can record:
$ arecord -l **** List of CAPTURE Hardware Devices **** card 1: H340 [Logitech USB Headset H340], device 0: USB Audio [USB Audio] Subdevices: 1/1 Subdevice #0: subdevice #0
In this case, I’m using a microphone that’s part of a Logitech USB headset with microphone. This is card 1, subdevice 0. We will need this information when we come to recording sounds.
To make the microphone active, you need to open the Audio Device Settings from the Preferences menu on your Raspberry Pi desktop. Then select your USB mic device from the “Sound card” list, as shown in Figure 15-6.
Next, click the Select Controls button and check the Microphone box. This adds a slider that allows you to control the gain of the microphone, and a red button at the bottom to turn it on and off (Figure 15-7).
Adjust the microphone gain slider up to about the 75% level.
You can now try to make a recording from the command line and then play it back. To record, use the following command:
$ arecord -D plughw:1,0 -d 3 test.wav
The -D
parameter specifies the device pluginhw:1,0
, which refers to the card number (1
) and subdevice (0
) that we discovered earlier.
To play back the sound you have just recorded, use the following:
$ aplay test.wav Playing WAVE 'test.wav' : Unsigned 8 bit, Rate 8000 Hz, Mono
You can interrupt the sound playing by using Ctrl-C.
I have had mixed results with the tiny push-in microphones like the one shown in Figure 15-5. Some work and some don’t. So, if you have followed the instructions here and you still can’t get your microphone to record anything, try a different one.
The arecord
command has optional parameters that allow you to control the sample rate and format of the audio you record. So, for example, if you want to record at 16,000 samples a second rather than the default of 8,000, use the following command:
$ arecord -r 16000 -D plughw:1,0 -d 3 test.wav
When you come to play back the sound, aplay
will automatically detect the sample rate, so you can just do this:
$ aplay test.wav Playing WAVE 'test.wav' : Unsigned 8 bit, Rate 16000 Hz, Mono
For ways of attaching a speaker to your Raspberry Pi, see Recipe 15.1.
For other methods of playing a sound file, see Recipe 15.3 and Recipe 15.4.
Use a piezo-electric buzzer connected to a general-purpose input/output (GPIO) pin.
Most small piezo buzzers work just fine using the arrangement shown in Figure 15-8. The one I used is an Adafruit-supplied component (see “Miscellaneous”). You can connect the buzzer pins directly to the Raspberry Pi using female-to-female headers (see “Prototyping Equipment and Kits”).
These buzzers use very little current. However, if you have a large buzzer or just want to play it safe, put a 470Ω resistor between the GPIO pin and the buzzer lead.
Paste the following code into an editor (ch_15_buzzer.py):
from
gpiozero
import
Buzzer
buzzer
=
Buzzer
(
18
)
def
buzz
(
pitch
,
duration
):
period
=
1.0
/
pitch
delay
=
period
/
2
cycles
=
int
(
duration
*
pitch
)
buzzer
.
beep
(
on_time
=
period
,
off_time
=
period
,
n
=
int
(
cycles
/
2
))
while
True
:
pitch_s
=
input
(
"Enter Pitch (200 to 2000): "
)
pitch
=
float
(
pitch_s
)
duration_s
=
input
(
"Enter Duration (seconds): "
)
duration
=
float
(
duration_s
)
buzz
(
pitch
,
duration
)
As with all the program examples in this book, you can also download this program (see Recipe 3.22). When you run the program, it first prompts you for the pitch in Hz and then for the duration of the buzz in seconds:
$ python3 ch_15_buzzer.py Enter Pitch (2000 to 10000): 2000 Enter Duration (seconds): 20
Piezo buzzers don’t have a wide range of frequencies, nor is the sound quality remotely good. However, you can vary the pitch a little. The frequency generated by the code is not very accurate, and you might hear a bit of warbling.
The program works by using the gpiozero
Buzzer
class to toggle the GPIO pin 18 on and off, with a short delay in between. The delay
is calculated from the pitch
. The higher the pitch
(frequency), the shorter the delay needs to be.
You can find the datasheet for the piezo buzzer here.
For better audio output options, see Recipe 15.1