Music With Ruby
WavesAlgorithms and ProgrammingDigital LiteracyComputing Systems

Music With Ruby

Grades 4–12
2 hr 35 min
12 steps
CSTAGrades 9, 10

Standards Alignment

CSTA

  • 1B-AP-10: Create programs that include sequences, events, loops, and conditionals.
  • 1B-AP-12: Modify, remix, or incorporate portions of an existing program into one's own work, to develop something new or add more advanced features.

Grades 9, 10

  • Explain that waves, such as light, seismic, sound waves, have energy and can transfer energy when they interact with matter.

Lesson Steps

1

👋 Welcome to Music with Ruby!

5 min

 

GETTING STARTED


 

 

What is Ruby?

 

Ruby is a programming language used throughout the world. If you've ever used Hulu, GitHub, Twitter, or Netflix, you've enjoyed products programmed with Ruby!

 

 

Programmers like Ruby because of its ease of use and its dynamic, general purpose function. We will use Ruby to create digital synths that you can actually play and enjoy.

Oh! There are 2 hidden memes in this project. Can you find them both?

 

 

Now you’re ready to code! Open a new tab or window to follow along with our myBetabox videos. Then, click on the next section to start!

2

⚙️ Setting Up Sonic Pi

15 min

Sonic Pi Setup

 

 

 

We will be using the program Sonic Pi to write code and create music! To install this program, simply visit www.sonic-pi.net in the browser of your choice and download the appropriate program for your operating system. Follow the downloading instructions on your computer.

 

 

Not Sure Which Version You Have?

 

To check which version your Operating System (OS) is, follow these steps:

 

Windows Users

 

The Edition will show you which version of Windows you're using.

 

 

Mac Users

 

Click the apple icon on the top left of your screen and select About This Mac from the drop down menu.

 

 

Note the version number as shown by the arrow.

 

 

Once you have done that, we can move on to exploring the interface!

3

⌨️ Keyboard Guide

5 min

Here are some handy guides for coding symbols. Hold the keys with a circle down at the same time.

Note: Mac users will use the command key instead of Ctrl.

 

Keyboard Guide


Save


: Colon = Shift + ;


_ Underscore = Shift + -


( Left Parenthesis = Shift + 9


) Right Parenthesis = Shift + 0


* Asterisk = Shift + 8

4

🎼 Musical Notes Introduction

15 min

BASICS OF CODING MUSIC





Keyboard Guide

Musical Notes Introduction

 

 

Here is a nifty note conversion chart. Experiment with some sounds!

 

 

The Code Explained

 

In this section, we will be learning simple ways to begin creating music. The simplest way to do this is to use what Sonic Pi refers to as “synths.” Generally speaking, synth is short for synthesizer which is a type of electronic instrument used to create music. Sonic Pi has support for many different synths but for now, we will just use the default to get started!

Sonic Pi allows you to start creating music immediately with note. When you hear that note, we refer to them as tones. Let’s give it a shot now!

To hear your sounds, hit run to run the code.

 

 

The notes you choose correspond to the notes of an instrument. You can use either a number or the note name.

To play the note numbered 60, type this:

 

play 60

 

If you type and run this code, you should then hear a tone played! Now obviously this is just one note. How do we go about changing that? What if we change the number to be higher or lower? What happens? Try replacing your code with something like the following:

 

play 100

 

You'll see that the higher the number, the higher the note. That means the lower the number, the lower the note!

It is generally advised that you stay within the range of 30 - 120. Anything outside of that range may be too high or low to be heard but experiences vary.

You can also use the note name and its octave to play a note. Reference the note conversion chart above to see which octave note correlates with what number. We can see that 60 is the same as C4 (C note in the 4th octave)! To code this with Ruby syntax, make sure to use a colon, like this:

 

play :C4

 

Try playing a few notes by writing three lines of code with different notes. Here's an example:

 

play 60
play :C4
play 22

 

I’m sure you probably noticed that all three notes played at the same time. This is because the computer runs so quickly that it executes each line almost simultaneously. This is great if we want to play all of the notes at the same time, like in chords, but what if we don’t? What if we want to create a sequence of notes or a melody.?

The sleep command acts like a rest between notes and allows notes to be heard one after the other.

 

sleep 1 codes for 1 beat rest
sleep 0.5 codes for a half-beat rest
sleep 2 codes for a 2 beat rest

 

Using the same notes, the melody can look something like this:

 

play 60 
sleep 1
play :C4 
sleep 1
play 22

 

You can even make sharp notes to jazz it up a little! These are notes that are a half-step higher and can be written like this:

 

play :Fs5 is an F# in the 5th octave
5

📻 Coding Familiar Songs

15 min
Keyboard Guide

Let's Code Simple Songs We Know

 

Musical Notes (with Octaves)

Sheet music will show notes on clefs like this. The top is the treble clef and the bottom is the bass clef, which is where you will find the lower-sounding notes. This image also shows us the octave these particular notes are in as indicated by the the small numbers.

 

 

Octave Chart

Want a bigger variety? On the left we have the bass clef octaves and on the right are the treble clef octaves. This chart can help you identify which notes fall under which octaves.

 

 

Note Symbols

 

Did you know an A sharp (A#) and a B flat (B♭) are the same note? Sharp notes are a half-step higher and flat notes are a half-step lower than the natural note. In the image below, you'll see that both A# and B♭ are indeed the same key.

 

Source: blog.flat.io

 

 

Jingles You May Know

Looking at this music sheet, we can code these notes into digital tones! A dotted note has a length of itself plus half. For example, the very last note is an eighth note but has a dot next to it. If eighth notes last for 0.50 beats, then a dotted eighth (de) last for 0.50 + 1/2(0.50) = 0.75 beats!

 

Copy & Paste This Code in Sonic Pi

 

#VARIABLES
e = 0.5 #eighth note
s = 0.25 #sixteenth note
de = 0.75 #dotted eighth note (e + 1/2e)

#TEMPO
use_bpm 100

play_pattern_timed [:Eb4, :F4, :G4, :C5, :Bb4, :G4, :F4, :Eb4, :Eb4], [e, e, e, s, e, e, e, s, de]

 

Another Example

 

 

Now that we know how to code notes, octaves, and can recognize notation, can you fill in the missing bars of this song? I've filled in the first two bars for you!

 

Copy & Paste this Code in Sonic Pi

 

#Blinding Lights
#Key Eb major

#VARIABLES
w = 4 #whole note
h = 2 #half note
q = 1 #quarter note
dq = 1.5 #dotted quarter note
sq = 4.5 #sustained quarter note (for this song)
e = 0.5 #eighth note
de = 0.75 #dotted eighth note
se = 1 #sustained eighth note (for this song)
s = 0.25 #sixteenth note
ds = 0.375 #dotted sixteenth note

#TEMPO
use_bpm 168

#CODE
play_pattern_timed [:F5, :F5, :Eb5], [h, dq, e]
play_pattern_timed [:F5, :G5, :C5, :Eb5], [e, q, se, dq]
play_pattern_timed [],[]
play_pattern_timed [],[]
play_pattern_timed [],[]
play_pattern_timed [],[]

 

 

Notes That Sound Good Together

 

Want to create your own sound? Using the notes in these chords will create a wonderful, melodious tune. Try different combinations!

 

Copy & Paste This Code into Sonic Pi

 

# What song is this? Do you recognize it?


play :F
sleep 0.16
play :G
sleep 0.16
play :As
sleep 0.16
play :G
sleep 0.16
play :D5
sleep 0.5
play :D5
sleep 0.5
play :C5
sleep 1

play :F
sleep 0.16
play :G
sleep 0.16
play :As
sleep 0.16
play :G
sleep 0.16
play :C5
sleep 0.5
play :C5
sleep 0.5
play :As
sleep 0.16
play :A
sleep 0.16
play :G
sleep 0.8

play :F
sleep 0.16
play :G
sleep 0.16
play :As
sleep 0.16
play :G
sleep 0.16
play :Bb4
sleep 0.7
play :C5
sleep 0.4
play :A
sleep 0.16
play :G
sleep 0.16
play :F
sleep 0.5
play :F
sleep 0.16
play :C5
sleep 0.5
play :As
sleep 1

play :F
sleep 0.16
play :G 
sleep 0.16
play :As 
sleep 0.16
play :G 
sleep 0.16
play :D5 
sleep 0.5
play :D5 
sleep 0.5
play :C5 
sleep 1

play :F 
sleep 0.16
play :G 
sleep 0.16
play :As 
sleep 0.16
play :G
sleep 0.16
play :F5 
sleep 0.6
play :A 
sleep 0.5
play :As 
sleep 0.16
play :A 
sleep 0.16
play :G 
sleep 0.8

play :F 
sleep 0.16
play :G 
sleep 0.16
play :As 
sleep 0.16
play :G 
sleep 0.16
play :As 
sleep 0.5
play :C5 
sleep 0.5
play :A 
sleep 0.16
play :G 
sleep 0.16
play :F
sleep 0.8
play :F 
sleep 0.2
play :C5 
sleep 0.4
play :As

 

 

Now It's Your Turn!

 

Using what we know so far, code a few lines of a fun song. Google can help you find the notes you're looking for. Use the charts above to figure out which octaves your notes are in!

Sonic Pi online keyboard

 

6

🔊 Amplify and Pan Notes

15 min
Keyboard Guide

Amplify and Pan Notes

 

 

The Code Explained

 

At this point, you may get tired of hearing the same repetitive beeps. The good news is we can easily change these up by adding options to our beeps. Options, or opts, come in many different flavors but we will start by talking about what they are and introducing the two most simple ones.

An opt is made up of two parts: the name and the value. The best way to explain this is to give you an example:

 

play 60, amp: 2

 

As you can see, I have added an extra bit of code to my regular play command. This code changes the amplitude, or loudness, of our note. Amp is the name of the opt and 2 is the value. This value can be anything from 0 to 5, including decimals! A value between 0 and 1 will cause the note to play quieter! Feel free to play around with this new opt and get a feel for how it works.

Want to change the loudness of your notes? Use amplify!

 

play :C4, amp: 2 makes this note twice as loud
play :C4, amp: 0.5 makes this note softer and plays half as loudly

 

Another popular opt, is the pan opt. This opt allows you to pick which side of your device plays out of using a value from -1 to 1. Numbers closer to -1 play out of the left side while numbers closed to 1 play out of the right side. Try out this example code:

 

play 60, pan: -1
sleep 1
play 60, pan: 0
sleep 1
play 60, pan: 1

 

You should hear three different notes play. One out of the left side, one out of both, and one out of the right side. This opt will allow you to add completely new dimensions to your music! Play around and see what you can create with this opt!

Want to give your sounds some direction? Use pan!

 

play :C4, pan: -1 to make sounds come from the left
play :C4, pan: 1 to make sounds come from the right
play :C4, pan: 0.5 to make  sounds come from the right but closer
play :C4, pan: 0 to make sounds come from the center

 

It is also important know that you can use multiple opts on a single note. This means that we could combine our amp and pan opts to create a whole new texture for our music! The only rules are that each opt has to be a different name and they must be separated by commas.

Now it's your turn! Play a note and give it different amp and pan effects. You can even use both at the same time! How do these notes change with these effects?

 

play 47
play 47, pan: -1, amp: 3
play 47, pan: 1, amp: 0.5
7

🎹 Changing Tones to Synths

15 min
Keyboard Guide

Changing Tones to Synths

 

 

The Code Explained

 

At this point, the same sounds may be getting pretty old. The good news is that Sonic Pi allows us to change up our sound by switching to other synths! 

Give your sounds some flair by using synths. The cool thing about Sonic Pi is that is comes with some awesome preloaded synths for you to use. It'll even autofill and pull up a selection menu for you to choose from! Type this code and see what happens:

 

play 60
sleep 1
use_synth :prophet
play 60
sleep 1
use_synth :chiplead
play 60
sleep 1

 

See how the same note changes after applying different synths?

If you'd like for the synths to play all at the same time, instead of one after the other, remove the sleep command, like this:

 

play 60
use_synth :prophet
play 60
use_synth :chiplead
play 60

 

Here's a list of synths you can use in Sonic Pi!

 

:blade
:bnoise
:chipbass
:chiplead
:chipnoise
:cnoise
:dark_ambience
:dpulse
:dsaw
:dtri
:dull_bell
:fm
:gnoise
:growl
:hollow
:hoover
:mod_beep
:mod_dsaw
:mod_fm
:mod_pulse
:mod_saw
:mod_sine
:mod_tri
:noise
:piano
:pluck
:pnoise
:pretty_bell
:prophet
:pulse
:saw
:sine
:square
:subpulse
:supersaw
:tb303
:tech_saws
:tri
:zawa

 

All of these synths are at your disposal, so I encourage you to play around with them and find what sounds you like best! What can you come up with?

8

📈 Understanding ADSR Envelopes

20 min
Keyboard Guide

Understanding ADSR Envelopes

 

 

The Code Explained

 

So far, we have learned to play different notes and allow for rests in between. What if we want to make our notes last for a longer amount of time? Luckily, we can easily do this and so much more by using ADSR Envelopes! An envelope is simply the name we give to the ADSR set of opts to avoid confusion. ADSR stands for

 

  • (A) Attack: how long it takes for a note to reach its peak volume from 0, akin to hitting a piano key.
  • (D) Decay: how long it takes for a note to go from its peak volume to its sustain value.
  • (S) Sustain: maintains the note, akin to a piano foot pedal.
  • (R) Release: how long it takes to go from its sustained value to the end of the note, akin to releasing a piano key.

 

and refers to the different stages of a note. The below graphic explains it best.

 

The only part of the envelope that is turned on by default is the release opt and it is always set to 1. You can set these numbers yourself by doing something like the following:

 

play :F4, attack: 1, decay: 0.5, sustain: 2, release: 3
Pro Tip: Adding an amp (like amp: 3) at the end can help you hear these notes better.

 

You don’t have to set all of the numbers if you don’t want to. Simply declaring one of them will also work! You may want to only use two of them and you can do that!

 

🌟  A release: 0 would have the note cut off immediately with no fading out and has a value of 0 instead of 1. This is a good technique for staccatos, arpeggios, and scales.

 

🌟  Coding attack: 0, sustain: 1 would make the note go from 0 straight to its sustained note. The same would happen it you omit attack and decay and start your code with a sustain instead.

 

The important thing to know is that your note will then last the duration of each of the ADSR numbers added together. This is called note length.

In the above example, the note length is 6.5 beats (1+0.5+2+3 = 6.5).

If you want a second note to play once the previous note has completed its full sound without overlap, insert a sleep command with the value being the note's note length between the two notes. In our example above, you would type something like this:

 

play :F4, attack: 1, decay: 0.5, sustain: 2, release: 3
sleep 6.5
play :B3

 

B3 will wait to start until F4 has finished playing.

If you do want an overlap between notes, make the sleep value less than the previous note length, like this:

 

play :F4, attack: 1, decay: 0.5, sustain: 2, release: 3
sleep 4
play :B3

 

In this case, B3 will start playing somewhere near the middle of F4's tone, creating an overlapping sound.

 

🌟  Keep this in mind! If you code attack: 1, decay: 0.5, sustain: 1 and do not include a release, the release would automatically be set to 1 and the note length would be 3.5 beats (1+0.5+1+1 = 3.5).
9

🎶 Adding Samples

15 min
Keyboard Guide

Adding Samples

 

 

The Code Explained

 

Now that we have successfully learned about synths, we can move on to the next important part of Sonic Pi... samples! Samples are basically clips of prerecorded sounds that you can use to really spice up your music. Many samples come preinstalled with Sonic Pi for you to use and are easy to add to your music!

Try this:

 

sample :ambi_lunar_land

 

You should now hear a spacey sound play and then stop. Pretty cool!

And just like with notes you can play multiple samples at the same time...

 

sample :ambi_lunar_land
sample :ambi_drone

 

...or play them in a sequence using the sleep command, like this:

 

sample :ambi_lunar_land
sleep 1
sample :ambi_drone

 

You may notice that these samples have some overlap. This is because the first sample is longer than 1 beat. This can be avoided by either making a longer sleep (higher sleep value) find the sample's note length.

But how do we do that? I don't see any numbers here like when we learned about ADSR envelopes, do you?

You can use a special command called sample_duration which automatically calculates the length of the sample for you. Try it out!

 

sample :ambi_lunar_land
sleep sample_duration :ambi_lunar_land
sample :ambi_drone

 

By using multiple commands (sleep, sample_duration) with two samples we can program the samples to play in a true sequence without overlap. Cool, huh?

Remember, you can also mix in notes with these sample commands to create something totally unique!

The last thing to note about samples is that there are a ton of them in Sonic Pi. You can easily scroll through all of them by using the auto-complete window that pops up when using the sample command (like with synths).

If you'd prefer to see the list here, take a look!

 

sample :ambi_
sample :bass_
sample :elec_
sample :perc_
sample :guit_
sample :drum_
sample :misc_
sample :bd_
sample :glitch_
sample :mehackit_
sample :vinyl_
sample :tabla_
sample :loop_
sample :sn_
10

🎚️ Modifying Samples

15 min
Keyboard Guide

Modifying Samples

 

 

The Code Explained

 

Now let’s look at how we can spice up our samples even more!

 

Sample Parameters

You may remember from earlier that we were able to add options to our notes to affect the way they sound. We can do the same thing with samples but here we refer to them as parameters. They work exactly the same way as before, so let’s take a look at our old friends amp and pan. You call these in the exact same way we did earlier as you can see in the following:

 

sample :loop_amen, pan: -1, amp: 2

 

This code will play the amen loop, panned to the left side, and amplified by 2. These parameters can be added to any sample you can imagine to create a whole new sound!

 

Stretching Samples

What if the sample you want to use is too short? What if its too long? Sonic Pi provides a way to deal with that in the form of another parameter called rate. Rate is used in a similar way to pan and amp and can be seen in use below:

 

sample :loop_amen, rate: 2

 

This code will play your sample twice as fast and make the pitch go up. What do you think would happen if you gave the parameter a value of -2? Run the following code to find out:

 

sample :loop_amen, rate: -2

 

This code will then reverse the sample and play it at twice the speed Using a negative value will reverse the sample and play it at the given rate!

 

sample :loop_amen, rate: 1 will play at normal speed
sample :loop_amen, rate: 2 will play at twice the speed
sample :loop_amen, rate: 0.5 will play at half the speed
sample :loop_amen, rate: -1 will play in reverse

 

The last thing to note is that using rate will cause your sample’s duration, or length, to be different. So if you are using sample_duration to space out your sounds you need to take that into account. The easiest way to do that is to use the formula

 (1 / rate) * sample_duration

to find your sample’s new duration. The following code is an example of that:

 

sample :loop_amen, rate: 0.5
sleep (1 / 0.5) * (sample_duration :loop_amen)
sample :loop_amen, rate: 2

 

It is very important that you remember to include the parenthesis, otherwise, the code will not run!

 

Samples with ADSR

Just like with notes, samples can have their ADSR envelopes set as well! The only difference is that you can’t use an envelope to lengthen a sample. The sample either stops at the end of the envelope or at the end of the sample, whichever comes first.

The first major use of these envelopes could be to fade in or fade out. To fade in you simply change the attack value. To fade out you need to change the release value. There is no need to change the sustain value unless you want to explicitly state how long it stays at full volume. An example of fading in and out follows:

 

sample :loop_amen, attack: 0.5, release: 0.5

 

You can hear from that code that our sample now fades in and then fades out. You can use one or both of these values to achieve different effects. All of these parameters can help to completely change the sound of a sample!

 

Partial Samples

We have already discussed one way to edit and chop up samples but Sonic Pi provides us with a second more powerful way to chop them up as well. We can actually declare a start and endpoint for our samples to just play parts of them.

The start can simply be declared by using the start parameter as you can see below:

 

sample :loop_amen, start: 0.5

 

This will cause the sample to start at the 0.5 second mark and play until the end.

You can also do the opposite and clip a sample so it ends before it's supposed to, like this:

 

sample :loop_amen, finish: 1

 

Want to only play the middle of a sample? You can see an example of this below:

 

sample :loop_amen, start: 0.5, finish: 1

 

This will cause the sample to only play the section, or segment,  between 0.5 and 1 seconds into it. This allows us to create new samples out of old samples.

Note: If your finish value is bigger than your start value, the segment will play in reverse.

Be aware that all of this can be combined with ADSR envelopes and other parameters to create really interesting effects!

11

💬 Morse Code Secret Message

15 min
Keyboard Guide

 

Using Morse Code with Sonic Pi

Morse Code is a type of cipher using dits (dots) and dashes to correspond with letters of the alphabet as well as numbers.

 

 


 

OPTION 1: USE TWO UNIQUE SAMPLES TO REPRESENT DOTS AND DASHES.

 

 

In this example I've coded the word SOW ( . . . / - - - / . - - )

The sample :bd_haus is short so we'll use it for dots and :bd_sone is longer so we'll use it for dashes. We can use the sleep sample_duration command to use the precise amount of time between beats.

Adding the sleep 3 command allows the code breaker to get ready for the next letter.

 


 

OPTION 2: MODIFY THE ATTACK AND RELEASE FOR THE SAME NOTE TO CREATE DOTS AND DASHES.

 

 

Using the same code word SOW, I'm modifying elements of the ADSR envelope to change the length of a note. I've chosen to modify note 60.  I'll use eighth notes (1/2 beat long) for dots and half notes (2 beats long) for dashes!

Remember that the note length in this case is the sum of the attack and release values. This is how to determine the sleep value.

Notice how I still used a sleep 3 command to give time between letters.

 


 

OPTION 3: MODIFYING THE SUSTAIN VALUES TO CREATE DOTS AND DASHES.

 

 

Alternatively, you can change the sustain values to make tones shorter or longer. Here I gave dots a smaller sustain value of 0.25 and the dashes have a longer value of 1. You can use any values you'd like!

Now it's time for you to create a Morse code for others to solve! Which method will you use?

 


 

Can You Crack This Code?

 

#Copy and paste in Sonic Pi


sample :bd_haus 
sleep sample_duration :bd_haus

sleep 3 
sample :bd_haus 
sleep sample_duration :bd_haus
sample :bd_haus
sleep sample_duration :bd_haus
sample :bd_haus
sleep sample_duration :bd_haus
sample :bd_sone
sleep sample_duration :bd_sone

sleep 3
sample :bd_haus 
sleep sample_duration :bd_haus
sample :bd_haus
sleep sample_duration :bd_haus

sleep 3
sample :bd_haus 
sleep sample_duration :bd_haus
sample :bd_sone
sleep sample_duration :bd_sone
sample :bd_haus
sleep sample_duration :bd_haus
sample :bd_haus
sleep sample_duration :bd_haus

sleep 3
sample :bd_sone 
sleep sample_duration :bd_sone
sample :bd_haus
sleep sample_duration :bd_haus
sample :bd_sone
sleep sample_duration :bd_sone

sleep 3
sample :bd_haus 
sleep sample_duration :bd_haus

sleep 3
sample :bd_haus 
sleep sample_duration :bd_haus
sample :bd_sone
sleep sample_duration :bd_sone
sample :bd_haus
sleep sample_duration :bd_haus

sleep 3
sample :bd_sone 
sleep sample_duration :bd_sone
sample :bd_sone
sleep sample_duration :bd_sone

sleep 3
sample :bd_haus 
sleep sample_duration :bd_haus
sample :bd_haus
sleep sample_duration :bd_haus

sleep 3
sample :bd_sone 
sleep sample_duration :bd_sone

 

Click here for the answer!

Materials

  • Computer with Sonic Pi installed — 1 per student

Ready to bring this lesson to your classroom?

Sign up to save this lesson, order supplies, and track student progress.