Making Music with Ruby and Sonic Pi

I've been coding in Ruby for years. Then I discovered you can make actual music with it. Not metaphorical music. Real sounds coming out of your speakers.

What is Sonic Pi?

Sonic Pi is a free tool that lets you write Ruby code that plays music. Dr. Sam Aaron built it at Cambridge University. You write code, hit run, and music comes out. It's that simple.

Download it from sonic-pi.net. Works on Mac, Windows, and Linux.

Your First Melody

Open Sonic Pi and paste this:

use_bpm 120

live_loop :melody do
  play :C4
  sleep 0.5
  play :E4
  sleep 0.5
  play :G4
  sleep 0.5
  play :B4
  sleep 0.5
end

Hit Run. You'll hear a simple arpeggio looping forever.

Here's what's happening:

  • use_bpm 120 sets the tempo to 120 beats per minute
  • live_loop creates a loop that keeps running
  • play :C4 plays middle C
  • sleep 0.5 waits half a beat before the next note

That's it. Four notes, looping. You just made music with Ruby.

Adding Some Depth

Let's make it more interesting. Add a bass line:

use_bpm 120

live_loop :melody do
  play :C4
  sleep 0.5
  play :E4
  sleep 0.5
  play :G4
  sleep 0.5
  play :B4
  sleep 0.5
end

live_loop :bass do
  play :C2, release: 2
  sleep 2
end

Now you have two loops running at once. The bass hits every 2 beats while the melody keeps going.

Randomness Makes It Fun

Want something less predictable? Use Ruby's randomness:

use_bpm 120

live_loop :random_melody do
  play choose([:C4, :E4, :G4, :B4])
  sleep 0.25
end

Now it picks random notes from your scale. Every run sounds different.

What You Can Build

Once you get the basics, you can go pretty far:

  • Algorithmic compositions - Let the code decide what to play next
  • Live coding performances - Change the music while it plays
  • Generative ambient music - Background sounds that never repeat
  • Teaching tool - Show kids that code can be creative

I started with simple loops. Now I use it for background music while working. The best part? You can tweak it in real-time. Change a number, hit run again, and the music shifts.

Getting Started

  1. Download Sonic Pi
  2. Paste the examples above
  3. Change the notes and timing
  4. See what happens

You don't need to know music theory. You don't need expensive software. Just Ruby and curiosity.

It's a fun side project. Give it 20 minutes and you'll have something playing.