Programming Meets Music with Sonic Pi

Article summary

At the recent GOTO Chicago conference, Sonic Pi creator Sam Aaron gave a rocking presentation about his code-turned-music program, which is aimed at getting anyone from kids to professional musicians interested in software development. After the keynote, Sam gave a performance for the conference, an entertaining demonstration of the power of code.

Sonic Pi is an open-source project, originally created at the University of Cambridge Computer Laboratory and supported by more than 200 contributors to the codebase. It combines programming with music, creating an environment that emphasizes coding while providing the enjoyment of music.

The base server is written in Ruby, giving the language for writing in Sonic Pi a familiar look and feel for experienced developers and an easy-to-learn interface for those new to programming.

Getting Started

Sonic Pi is available free for Windows, macOS, and Raspberry Pi. (In fact, it comes pre-installed on all Raspberry Pi.) The documentation can be found online or within the program itself.

Beeps and beats

Music can be something as simple as notes with a beat, so let’s start with that. To have Sonic Pi play a note, we just say play. With play, we give a number to denote the note; higher numbers are higher notes and vice versa.


play 75

Beats can be created using samples—pre-recorded music that’s provided through Sonic Pi. They can range anywhere from a bass to a guitar to percussion. Once you find a sample you want to use (via auto-complete or the system help option), you can drop it in using the name.


sample :perc_bell

Now that we have a beat and some beeps, we want to make it play continuously. That’s where live loops come in.

Live loops

The first important line of code to learn for Sonic Pi is the live loop. Just like it sounds, the live loop allows you to write a code within a loop to play continuously while you edit it. Yes, just like playing a guitar, you can change the music up as it’s playing! According to the documentation, live loop is the best way to jam with Sonic Pi.

Creating a live loop is simple: just create a loop and start adding your music to it.


live_loop :foo do
# Your music goes here!
end

As long as you don’t hit Stop, any time you make a change, the music will reflect it LIVE!

The best way to learn Sonic Pi is to try it out for yourself. Explore the program, documentation, and music that others have created to discover all the ways you can create music while practicing coding.