Programming Music

Rengarajan
3 min readAug 27, 2020

A novice attempt at learning music via programming

Photo by Omar Prestwich on Unsplash

Instead of picking up an instrument, learning music theory or any other type of formal training, I recently got interested in learning music via programming. Enter Sonic Pi.

Sonic Pi is a music programming environment, which lets you write code and execute it on the fly. The output as expected is sound, MIDI sounds to be specific. Sonic Pi was created by Sam Aaron as a tool to be used in schools for teaching computing and music. I should say it achieves this in spades. My 9 year old son, just loves to make sounds using Sonic Pi.

Internally Sonic Pi uses SuperCollider as its audio synthesis engine. But for all practical purposes we don’t need to worry about it. If you see a background process named scsynth then know that it’s SuperCollider.

The language itself is based on Ruby and it’s very novice friendly environment. The simplest sound is a note and you can play one by simply typing the following into the Sonic Pi buffer.

play 72

Not so fancy, how about we graduate to a small melody.

play 72
sleep 1
play 75
sleep 1
play 79

If you are more music savvy then you can use note names instead of the numbers

play :C
sleep 1
play :D
sleep 1
play :E

Now this is a small little melody and after each note, you see there is a sleep which essentially means skip a beat. Of course you can use half a beat (0.5) as well.

Ok, now lets say I want to play this 10 times,

10.times do
play :C
sleep 1
play :D
sleep 1
play :E
end

You can also play sounds indefinitely or until you press the stop button using

loop do
sample :drum_bass_soft
sleep sample_duration :drum_bass_soft
end

Timing in music is everything and it’s not good enough just to play the toy programs alone, but there are variety of things that are involved in composing music like different instruments, melodies, beats, effects etc. and all of them needs to work seamlessly to make harmonious music.

This is where serious computer science kicks in, Sonic Pi supports multi-threading as one of the first class constructs so that you can weave different parts of your music together at the same time.

in_thread do
loop do
sample :ambi_choir
sleep 2
end
end
loop do
use_synth :mod_fm
play :E2, release: 0.2
sleep 1
end

For an in-depth understanding of how timing works in Sonic Pi you can read the paper here

There are tons of other features in Sonic Pi like synths, effects which you can control, tweak and make awesome music.

Live Coding

Sonic Pi is not just for beginners but serious musicians and live code performers use it to create and perform music. Here is a short introductory video

The following are few other LiveCoding / music programming alternatives

--

--

Rengarajan

Software Engineer | Passionate Learner | Lifelong Student