Accidentally Learn To Program With Sonic Pi Episode 1

Did you know you could learn to program by accident without even realising? In this post we’re going to do exactly that! Really, all we’re going to do is to teach you how to make your own sounds on the Raspberry Pi and you’ll find that you’ll accidentally learn to program at the same time. Sound fun? Well let’s get going…

Before we start, let’s cover some deeply theoretical music theory as it’s fundamental to our journey…

Music can have notes.

That’s it! That’s the theory. There are notes. There are high notes, and low notes and notes in between. Lots and lots of notes. Just like there are lots of numbers, high numbers, low numbers and numbers in between. In fact we can use numbers to represent our notes. So, let’s get started.

Open up the Sonic Pi app

(if it’s not installed on your RP, simply attach it to a network and run sudo apt-get update and sudo apt-get install sonic-pi).

You’ll see three panes - a large one on the left and two small ones on the right. Click in the large pane on the left and type the following:

play 60

Stick some headphones or a speaker into your RP and then hit the play button (a little triangle) at the top left of the app window…


How easy was that? If you’ve never coded before, that was your first ever program. Really, it was. Programming is easy and fun. Go and tell your friends!

Try playing around with different numbers. What happens if you choose really low numbers like: play 5 or really high numbers like play 500? You’ll find that some numbers are too high or low to hear! As a guide, you might want to stick between 30-80.

Let’s play two notes at the same time:

play 60
play 65

Fun! Try playing lots of notes, and see what happens…

Let’s learn one more thing. To stop all our notes sounding at once and making a big fun messy loud sound, we can spread them out a bit. This is pretty easy - all we need to do is not play them at the same time. We can play one note, wait a bit, and then play another. Waiting is easy with Sonic Pi, just use the sleep command. Try typing in the following:

play 60
sleep 0.25
play 65
sleep 0.5
play 72

The number used with sleep is the number of seconds to wait for. 0.5 seconds happens to be half a second, and 0.25 is a quarter of a second.

Now, don’t stop there. That tune is rubbish! Make your own, try lots of different notes and different sleep times and have fun composing your own piece.

Posted by Sam Aaron on 13 September 2013. » all posts