Last time we saw how to connect an amplifier and speakers to the Raspberry, now we’ll look at playing some sound with the SDL2_mixer library, but first we’ll have to enable sound. As I said in my previous post, sound on the Raspberry Pi is not as straightforward as you’d like it to be, so there are quite some steps involved to get it working properly.

# Enabling the sound module

First off, we’ll need to ensure the sound module is enabled:

If you don’t see snd_bcm2835, you’ll have to enable the module:

Try rebooting and check whether the module is loaded properly. If it still isn’t, edit the modules file:

# Enabling sound output over the 3.5mm jack

By default the Raspberry outputs its sound over the HDMI port, but this is not what we want. To enable the sound output over the 3.5mm jack, run the following command:

If you want to enable sound output over a different output, change the 1 in the command to a different number: 0 for auto, 1 for analog and 2 for HDMI

# Testing the output

for testing the output, we’ll first need to check whether OMXPlayer is installed. To do this, run the following command:

If you get a message that the command isn’t found, install it:

Now, cd into a directory containing an MP3-file, and run the following command:

If everything works, you should hear music playing over your sound output.

# Installing SDL2

The easiest way of getting SDL2 on your Pi is by just downloading binaries from here, unzip it and move the folders in local to /usr/local/bin, /usr/local/include and /usr/local/lib respectively. Note that SDL2_mixer is not included, so we’ll have to build that ourselves.

To do this, download it from here, unzip it and cd into the directory. Then execute the default steps for building a linux library (the make command will probably take quite some time):

# Playing some sound

So, finally, we can play some sound using SDL2 and C++:

and build it:

Note that I’m using an ogg-file instead of MP3, that is because MP3 didn’t work for me, and it’s quite easy to convert .mp3 to .ogg using audacity

# Cranking up the volume

You might notice that the volume using SDL is quite low compared to OMXPlayer, but this is easily solvable:

If you want a different volume, replace the 100%. Also, you’ll have to run this command every time you reboot your Pi, so I advice putting it in some sort of initialization script.