How to play sound and make noise with your Raspberry Pi
If your amazing project is a little too quiet, add high-fidelity sound with Raspberry Pi and the help of this handy guide from HackSpace magazine, written by PJ Evans.
It’s no surprise that we love microcontrollers at HackSpace magazine. Their versatility and simplicity make them a must for electronics projects. Although a dab hand at reading sensors or illuminating LEDs, Arduinos and their friends do struggle when it comes to high-quality audio. If you need to add music or speech to your project, it may be worth getting a Raspberry Pi computer to do the heavy lifting. We’re going to look at the various audio output options available for our favourite small computer, from a simple buzz, through to audiophile bliss.
The simplest place to start is with the humble buzzer. A cheap active buzzer can be quickly added to Raspberry Pi’s GPIO. It’s surprisingly easy too. Try connecting a buzzer’s red wire (positive) to GPIO pin 22 (Broadcom numbering) and the black wire (ground) to any GND pin. Now, install the GPIO Zero Python library by typing this at the command line:
sudo apt install python3-gpiozero
Create a file called
buzz.py in your favourite editor and enter the following:
import time from gpiozero import Buzzer buzzer = Buzzer(22) buzzer.on() time.sleep(1) buzzer.off()
Run it at the command line:
You should hear a one-second buzz. See if you can make Morse code sounds by changing the duration of the
Passive but not aggressive
Raspberry Pi computers, with the exception of the Zero range, all have audio output on board. The original Raspberry Pi featured a stereo 3.5mm socket, and all A and B models since feature a four-pole socket that also includes composite video. This provides your cheapest route to getting audio from your Raspberry Pi computer.
A low-cost passive speaker can be directly plugged in to provide sound, albeit probably quieter than you’d like. Of course, add an amplifier or active speaker and you have sound as loud as you like. This is the most direct way of adding sound to your project, but how to get the sound out?
Normally, the Raspbian operating system will recognise that an audio device has been connected and route audio through it. Sometimes, especially if you’ve connected an HDMI monitor with sound capability (e.g. an HDMI TV), sound will not come out of the correct device.
To fix this, open up a terminal window and run
sudo raspi-config. When the menu appears, go to Advanced Options and select Audio, then select the option to force the output through the audio jack. You may need to reboot Raspbian for all changes to take effect.
Plug and playback
A USB sound device is another simple choice for audio playback on Raspberry Pi. Literally hundreds are available, and a basic input/output device with better audio quality than the on-board system can be purchased for a few pounds online. Installation tends to be no more complicated than plugging the device into the USB port. You may need to select the new output, as the underlying audio system, ALSA (see the ALSA and PulseAudio section for more), may mute it by default. To fix this, run
alsamixer from the command line, press
F6 to select the new sound device, and if you see ‘MM’ at the bottom of the volume indicator, press
M to unmute and adjust the volume with the cursor keys.
Unsurprisingly, when choosing your USB sound device, you can start at a few pounds and go right up to professional equipment costing hundreds. As they are low-power, USB devices do not tend to feature amplification, unless they have a separate power source.
The simplest way to play audio on Raspbian is to use OMXPlayer. This is a dedicated hardware-accelerated command-line tool that takes full advantage of Raspberry Pi’s capabilities. It sends audio to the analogue audio jack by default, so playing back an MP3 file is as simple as running:
There are many command-line options that allow you to control how the audio is played. Want the audio to loop forever? Just add
--loop to the command. You’ll notice that when it’s running, OMXPlayer provides a user interface of sorts, allowing you to control playback from within the terminal. If you’d just like it to run in the background without user input, run the command like this:
omxplayer --no-keys example.wav &
—-no-keys removes the interface, and the ampersand (&) tells the operating system to run the job ‘in the background’ so that it won’t block anything else you want to do.
OMXPlayer is a great choice for Raspbian, but other players such as mpg321 are available, so find the tool that’s best for you.
Another useful utility is
speaker-test. This can produce white noise or vocal confirmation so you can check your speakers are working properly. It’s as simple as this:
speaker-test -t wav -c 2
The first parameter sets the sound to be a voice, and the
-c tests stereo channels only: front left and front right.
If space is an issue, a Raspberry Pi 4, amplifier, and speaker may not be what you have in mind. After all, your cool wearable project is going to be problematic if you’re trailing an amplifier on a cart with a 50-metre extension lead powering everything. Luckily, the clever people at Pimoroni have you covered. The Speaker pHAT is a Raspberry Pi Zero-sized HAT that not only adds audio capability to the smallest of the Raspberry Pi family, but also sports a 3 W speaker. Now you can play any audio with a tiny device and a USB battery pack.
The installation process is fully automated, so no messing around with drivers and config files. Once the script has completed, you can run any audio tool as before, and the sound will be routed through the speaker. No, the maximum volume won’t be troubling any heavy metal concerts, but you can’t knock the convenience and form factor.
Playing the blues
An easy way to get superior audio quality using a Raspberry Pi computer is Bluetooth. Recent models such as the 3B, 4, and even the Zero W support Bluetooth devices, and can be paired with most Bluetooth speakers, even from the command line. Once connected, you have a range of options on size and output power, plus the advantage of wireless connectivity.
Setting up a Bluetooth connection, especially if you are using the command line, can be a little challenging (see the Bluetooth cheatsheet section). There is a succinct guide here: hsmag.cc/N6p2IB. If you are using Raspbian Desktop, it’s a lot easier. Simply click on the Bluetooth logo on the top-right, and follow the instructions to pair your device.
If you find OMXPlayer isn’t outputting any audio, try installing mpg321:
sudo apt install mpg321
And try again:
If your project needs good audio, and the standard 3.5 mm output just isn’t cutting it, then it’s time to look at the wide range of DACs (digital-to-analogue converters) available in HAT format. It’s a crowded market, and the prices vary significantly depending on what you want from your device. Let’s start at the lower end, with major player HiFiBerry’s DAC+ Zero. This tiny HAT adds 192kHz/24-bit playback via two RCA phono ports for £12.50. If you’re serious about your audio, then you can consider the firm’s full HAT format high-resolution DAC+ Pro for £36, or really go for it with the DSP (digital sound processing) version for £67. All of these will require amplification, but the sound quality will rival audio components of a much higher price.
If money is no object and your project requires the best possible reproduction, then you can consider going full audiophile. There are some amazing high-end HATs out there, but one of the best-performing ones we’ve seen is the PecanPi DAC. Its creator Leonid Ayzenshtat sourced each individual component carefully, always choosing the best-in-class. He even used a separate DAC for each audio channel. The resulting board may make your wallet wince at around £200 for the bare board, but the resulting audio is good enough to be used in professional recording studios. If you’ve restored a gorgeous old radio back to showroom condition, you could do a lot worse than add the board in with a great amp and speaker.
ALSA and PulseAudio
There’s often confusion between these two systems. Raspbian comes pre-installed with ALSA (Advanced Linux Sound Architecture), which is the low-level software that makes sound work. It comes with a range of utilities to control output device, volume, and more. PulseAudio is a software layer that sits on top of ALSA to provide more features, including streaming capabilities. Chances are, if you need to do something a bit more clever than just play audio, you’ll need to install a PulseAudio server.
If you want to pair a Bluetooth audio device (A2DP) on the command line, it can be a little hairy. Here’s a quick guide:
sudo apt-get install pulseaudio pulseaudio-module-bluetooth sudo usermod -G bluetooth -a pi sudo reboot
Start the PulseAudio server:
Run the Bluetooth utility:
Put your speaker into pairing mode. Now, within the utility, run the following commands (pressing Enter after each one):
power on agent on scan on
Now wait for the list to populate. When you see your device…
<dev> is the displayed long identifier for your device. You can just type in the first few characters and press Tab to auto-complete. Do the same for the following steps.
trust <dev> connect <dev>
Wait for the confirmation, then enter:
Now try to play some audio using aplay (for WAV files) or mpg321 (for mp3). These instructions are adapted from the guide by Actuino at hsmag.cc/N6p2IB.
There are command-line players available for just about every audio format in common use. Generally, MP3 provides the best balance of quality and space, but lower bit-rates result in lower sound quality. WAV is completely uncompressed, but can eat up your SSD card. If you don’t want to compromise on audio quality, try FLAC, which is identical in quality to WAV, but much smaller. To convert between audio types, consider installing FFmpeg, a powerful audio and video processing tool.
This article comes direct from HackSpace magazine issue 28, out now and available in print from your local newsagent, the Raspberry Pi Store in Cambridge, and online from Raspberry Pi Press.
If you love HackSpace magazine as much as we do, why not have a look at the subscription offers available, including the 12-month deal that comes with a free Adafruit Circuit Playground! Subscribers in the USA can now get a 12-month subscription for $60 when joining by the end of March!
And, as always, you can download the free PDF from the Raspberry Pi Press website.
I’ve always wondered why Sonos-like systems are so expensive given that you can get a full computer in the Pi Zero-W for a tenner.
Are there instructions for going the extra step and using one or more Pis to create wireless stereo smart-speakers and home streaming systems with a feature set equivalent to Sonos, etc., somewhere?
Have a look at volumio. With the right DAC and amp combi you can get HiFi sound for under £100 (if you already have the speakers).
Have a look at max2play.com. I use two stereo systems and two old transistor radios as my multiroom system. Perfectly in sync. Operated via two RPi 3 with a DAC HAT by hifiberry and two RPi zero with a small HAT Amp (build into the radios, powered by a powerbank, also build into the radio). Works great. My CD collection is on a hard disc (lossless format). I am using the setup for about three years now. Used Volumio, which is great also and easy to setup, but switched to max2play because of the better multiroom (might have changed meanwhile). Enjoy :-)
Another vote here for max2play. I run this on a Pi3 with all my music (20,000 tracks) on a USB drive. Max2play is controlled by Squeezebox apps on my phone and PC or via a browser. This server has no audio output but broadcasts over wifi to two Pi3s with HiFiBerry DACs running Moode in Squeezelite mode connected to amps and speakers in the kitchen and library. There’s also a Pi4 running Kodi with a Squeezelite addon that plays through the home cinema receiver in the living room. All perfectly synchronised, usually playing my music collection, Radio Paradise or BBC Radio 4.
Also consider piCorePlayer and LMS (Logitech Media Server).
I have a Zero W with a pHat DAC and cheap amplifier and speakers streaming audio from my LMS, and the sound quality is plenty good enough. You can control such a streamer from a web browser on the same network, a phone app, a dedicated Logitech Squeezebox controller, or from a touch screen on a Pi.
This system also lets you sync multiple players so that you can have the same playlist playing throughout the house.
Re: sonos pi: getting a sound signal is cheap… choosing a speaker and appropriate enclosure is more difficult. Then writing software to synchronise the sound between speakers / rooms is particularly tricky. I tried to make a pi-based client of my Naim hi-fi but got stuck at ensuring each sample was output at the correct millisecond.
There might be a free multi-room protocol / library / daemon I’m not aware of that might do the heavy lifting.
For basic wi-fi speaker functionality there are loads of guides… search for Max2Play and Volumio.
Wish I had seen this about a month ago. I bought one of the Sonos5 1st gen that had been lobotomized by the upgrade. The speakers and housing work great. I hoped to separate the amp from the controls but no luck. I ended up with a 2.1 bluetooth amp connected to the gutted housing. It works well but going to a Pi would have been really great.
i have a question…
such a buzzer like on the picture, does it only make one buzzer sound, or can it be used as tiny loudspeaker too?
i am asking, because on my PC mainboard there such a looking device, but it does more different sounds than only beeping.
so it there a different to that tiny loudspeaker and a buzzer… both looking exactly equal – opticaly.
the problem is, i only can find buzzers at my local store.
does a buzzer can be driven with PWM and gives useful sounds like the old tiny games?
There are buzzers, devices that turn a DC voltage into a sound with internal electronics, and there are tiny speakers that look exactly like those buzzers, but have no electronics inside, but instead are just miniature “loudspeakers”.
both look exactly alike, and their form-factor is a kind of de facto standard.
Given that a GPIO can only (safely) deliver a tiny amount of current (15mA) at 3.3Volt both the buzzer and the speaker should not be directly powered from a GPIO, and the speaker should be connected to the AV output rather than a GPIO. Also a GPIO will only be able to output a square wave, limiting what sound can be emitted (or you need to use it as a PWM signal, and filter it, that is what the AV output does)
thank you for your answer…
i want them only to play primitive melodies like the old LCD games or electronic bithday greeting cards.
confusing… when i search for it, it tells PC motherboard speaker buzzer… that suggest that it is a buzzer and a speaker, depending how you drive it…
is it a buzzer or speaker…
even wors, when i use those keywords on a german electronic store, i get only piezo buzzer those looks like the black capsule or a pc big speaker with paper membrane …
The piezo-electric transducer which is the basis of both the buzzer and “speaker” can be used for either, provided it has no driver electronics. If you drive it with a simple low-frequency square-wave, it will buzz. A sine wave will cause it to whine or whistle depending on frequency and, if you feed it audio, it will reproduce that sound track.
Why are there no ADC microphone HATs?
I invested in a couple of Cambridge Audio StreamMagic DACs 5 years ago which costed $5,000, but after a lot of experimenting with other DACs, I now run a Pi4 4Gb with a SMSL SK10 USB DAC attached to my $20,000 Stero System, and a Pi4 2GB with Topping D30 in the bedroom. Both Cambridge Audio DACs are now used to lissen to the TV’s TOS-Link Audio output.
My 50+ years of collecting Music is slowly being copied to an ASUSTOR NAS with twin Mirrored 8Tb Drives. I use Volumio to transfer the stored FLAC Audio Files to the USB DAC via a Pi4.
I suggest you look at Volumio as the Interface to play your music, and invest in a USB DAC, such as a Topping D30 (or D50), or a SMSL SK10 High-end 32Bit/768kHZ. I insist you build or buy a 5Volt, 5Amp LINEAR Type Powersupply to power the Pi and DAC. You won’t regret it, as the Pi4 Powersupply doesn’t make the grade in this application because of the Noise produced with a Switching type Powersupply.
When the Pi with USB DAC is plugged into a decent Class ‘A’ (“Steam Powered” Valve/Tube) Power Amplifier, you will become the envy of all your mates…
The other advantage of using a USB DAC, is the fact it is easy to upgrade given to this Technological Wirlwind, which continues to bring forth better and cheaper electronics.
Comments are closed