Playing sounds on the Raspberry Pi

Today at Raspberry Pi club, myself and some of the children worked out how to add sounds to their games. The steps you go through are relatively simple, but I thought it useful to document them here for others to benefit from.

HDMI or 3.5mm Jack?

We’ve been fiddling occasionally at a school Raspberry Pi club trying to get our integral speakers working on our TidyPi machines, and never quite got it working. Here is the TidyPi, in case you forget what it looks like:

The monitors we rescued from an old computer lab, have stereo speakers in the front, which we plug into the Pi using a 3.5mm jack plug. But for some reason they never seemed to work.

We fiddled with the obvious like using the on screen menus on the monitor to raise the volume, but still nothing.

I remember @MissPhilbin saying about the audio mixer control, so we tried this:

sudo amixer cset numid=3 100%

Still no sound. It was one of our YR10 lads that had a bright idea, that it was something to do with our HDMI adaptor. We use a CableMatters HDMI to VGA adaptor on all our Pi’s – the hunch being that because we had something plugged into the HDMI, the Pi had sensed it and routed to HDMI audio (even though those adaptors have no way of processing the audio).

A quick check, and we tried this:

sudo amixer cset numid=3 1

Success! We had HomerSimpson.wav blasting out of our speakers!

The “1″ at the end of the command selects the headphone socket

Doing something useful in python/pygame

I remember another one of our lads from the Saturday club saying he had looked at the pygame sound module but found it a bit confusing to set up. So, after a bit of a read up on the pygame website, we came up with this short “building block” that we’re going to use to add sound to all our games now!

import pygame
s = pygame.mixer.Sound("HomerSimpson.wav")

There are some useful options to the sounds that you can set, follow the pygame docs in the links at the end. The most useful to know is that the sound mixer in pygame is multi-channel, so here is a design pattern that allows you to play a background music sound and then also play “event sounds” when things collide or get shot:

import pygame
import time

background = pygame.mixer.Sound("music.wav") # loops indefinitely

bang = pygame.mixer.Sound("bang.wav")
while True:

I imagine that next week we’ll have all sorts of interesting sounds coming out of space invaders and pong!


[1] Sound configuration

[2] Routing to the headphone jack

[3] pygame sound mixer

[4] CableMatters HDMI to VGA Adaptor


This entry was posted in How to, Raspberry Pi. Bookmark the permalink.

Comments are closed.