Miskatonic University Press

Clapping Music on Sonic Pi

code music raspberry.pi sonic.pi

A while ago I bought a Raspberry Pi, a very small and cheap computer, and I never did much with it. Then a few days ago I installed Sonic Pi on it and I’ve been having a lot of fun. (You don’t need to run it on a Pi, you can run it on Linux, Mac OS X or Windows, but I’m running it on my Pi and displaying it on my Ubuntu laptop.)

My Raspberry Pi
My Raspberry Pi.

Sonic Pi is a friendly and easy-to-use GUI front end that puts Ruby on top of SuperCollider, “a programming language for real time audio synthesis and algorithmic composition.” SuperCollider is a bit daunting, but Sonic Pi makes it pretty easy to write programs that make music.

I’ve written before about “Clapping Music” by Steve Reich, who I count as one of my favourite composers: I enjoy his music enormously and listen to it every week. “Clapping Music” is written for two performers who begin by clapping out the same 12-beat rhythm eight times, then go out of phase: the first performer keeps clapping the same rhythm, but the second one claps a variation where the first beat is moved to the end of the 12 beats, so the second becomes first. That phasing keeps on until it wraps around on the 13 repetition and they are back in phase.

Here’s one animated version showing how the patterns shift:

And here’s another:

Here’s the code to have your Pi perform a rather mechanical version of the piece. The clapping array defines when a clap should be made. There are 13 cycles that run through the clapping array 4 times each. The first time through cycle is 0, and the two tom sounds are the same. The second time through cycle is 1, so the second tom is playing one beat ahead. Third time through cycle is 2, so the second tom is two beats ahead. It’s modulo 12 so it can wrap around: if the second tom is on the fifth cycle and ten beats in, there’s no 15th beat, so it needs to play the third beat.

use_bpm 300

load_sample :drum_tom_lo_soft
load_sample :drum_tom_mid_soft

clapping = [1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0]

13.times do |cycle|
  puts "Cycle: #{cycle}"
  4.times do |reps|
    12.times do |beat|
      sample :drum_tom_lo_soft, pan: -0.5 if clapping[beat] == 1
      sample :drum_tom_mid_soft, attack: 0.05, pan:  0.5 if clapping[(cycle + beat) % 12] == 1
      sleep 1

If you’re running Sonic Pi, just paste that in and it will work. It sounds like this (Ogg format):

It only does four repetitions of each cycle because my Pi is old and not very powerful and for some reason eight made it go wonky. It’s not perfect even now, but the mistakes are minimal. I think a more recent and more powerful Pi would be all right, as would running Sonic Pi on a laptop or desktop.

It’s lacking all the excitement of a performance by real humans (some of which could be faked with a bit of randomization and effects), but it’s very cool to be able to do this. Algorithmic music turned into code!