Chapter 8. Exploring Sound with the Raspberry Pi 2

In this chapter we will explore generating audio on the Raspberry Pi. This will include:

We will first learn how to configure the Raspberry Pi to switch between either the analogue or digital (HDMI) sound outputs.

Following this, we will discover how we can use the GPIO pins to provide input for playing sounds on the Raspberry Pi via Python. This will introduce us to ALSA. ALSA stands for Advanced Linux Sound Architecture and provides audio and MIDI support to Raspbian.

After looking at audio via Python, we will then move on to see how ALSA is implemented in C and how programs can be written that incorporate it.

Our final exploration of sound on the Raspberry Pi will lead us to Sonic Pi. You will discover how you can write scripts in the GUI that play a variety of sounds and ultimately allow you to construct your own music.

So let's get started with a brief recap on the Raspberry Pi 2's sound hardware.

There are several options for outputting sound on the Raspberry Pi 2. The first is the HDMI port. If you are using this connected to a HDTV, for example, you can stream both video and audio at the same time.

The second is the analogue audio jack. This is perfect for attaching headphones or speakers that use a headphone-style plug.

However, we are not limited to these two methods.

As explained in Chapter 1, Introduction to the Raspberry Pi's Architecture and Setup, the Raspberry Pi 2 implements an Inter-IC Sound (I2S) serial bus for both audio input and output.

From the Raspberry Pi's perspective, implementing I2S allows us to not only use HDMI and the analogue audio jack, but also implement audio via the GPIO pins or USB.

We can therefore connect an external device to, say, our GPIO pins that can act as a HiFi system. Later in this chapter we will look at some example hardware that does exactly this.

I2S can be found in a variety of other audio products, including CD players, due to its ability to communicate digital audio data between microchips. You can read more about the specification at https://en.wikipedia.org/wiki/I%C2%B2S.

The Raspberry Pi 2 gives us the ability to configure which of our audio outputs we want to use. In this chapter we will build a device that accepts input from the GPIO pins and outputs it to either speakers or headphones connected to the 3.5 mm jack.

Our first task therefore is going to be to understand how we can set the audio output mode.