Music With Ruby: B-Side Remix
WavesAlgorithms and ProgrammingDigital LiteracyComputing Systems

Music With Ruby: B-Side Remix

Grades 4–12
1 hr 30 min
10 steps
CSTA

Standards Alignment

CSTA

  • 1B-AP-10: Create programs that include sequences, events, loops, and conditionals.
  • 2-AP-11: Create clearly named variables that represent different data types and perform operations on their values.
  • 2-AP-12: Design and iteratively develop programs that combine control structures, including nested loops and compound conditionals.
  • 2-AP-14: Create procedures with parameters to organize code and make it easier to reuse.

Lesson Steps

1

👋 Welcome to Music with Ruby!

5 min

 

GETTING STARTED


 

Welcome to the B-Sides Remix!

 

This is a follow-up to the Music with Ruby project. If you haven't checked it out yet, click here!

 

Now that we've covered some of the basics of coding music with Ruby, let's take it a step further with more advanced code! If you see something like this...

 

loop do
    sample :loop_amen
    sleep sample_duration :loop_amen
end

sample :drum_cymbal_open

 

...you can copy and paste the code directly into Sonic Pi!

Now, open up Sonic Pi and click the next section to begin.

 

2

⌨️ 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

3

🔁 Iterations

15 min

CODING MUSIC




Keyboard Guide

Iterations (Loops!)

 

 

The Code Explained


 

Iteration

 

Sometimes in Sonic Pi you may want to do something multiple times. You could just type out your code over and over but there is a much easier way to do this and it is by using loops! Loops will allow you to reuse code and run it multiple times or even allow you to play sections until you press stop. Take a look at the example code below and decide which you would rather type this...

 

play 65
sleep 1
play 65
sleep 1
play 65
sleep 1
play 65
sleep 1
play 65
sleep 1
play 65
sleep 1
play 65
sleep 1
play 65
sleep 1
play 65
sleep 1
play 65
sleep 1

 

...or this?

10.times do
    play 65
    sleep 1
end

 

The second one is obviously easier to type and you will get the exact same result.

 

Let’s break down the parts of a loop now. First, you have the times component which will tell your loop how many times you want to run the code contained in the loop.

Next, you have the do keyword which simply tells the computer that this is where the loop begins. Now you can type whatever code you want inside the loop to be repeated.

It is important that you have the tabs or whitespace so that your code is readable. To push those lines over, use the tab key on your keyboard.

Finally, you must end the loop by using the end keyword. Try putting all this together and give it a shot!


 

Nesting Iterations

 

It is also possible to put a loop inside of a loop. This process is known as nesting in the computer science world. Look below to see an example of nesting:

 

4.times do
    2.times do
        sample :elec_blip2, rate: 2
        sleep 0.25
    end
    4.times do
        sample :drum_tom_mid_soft
        sleep 0.125
    end
end

 

As you can see, we have put two loops inside of our main 4.times loop. This means that we will hear the pattern inside the main loop play 4 times and each of those loops will play the respective amounts. I know this can be confusing at first but it really helps to unleash the power of code. An easy way to find out how many times a part of the loop will play is to multiple both loop numbers together.

 

🌟  Remember that for every do keyword you must have an end keyword.

 


 

Looping

 

Iterations are great if you want to play something a set amount of times but what if you want to play something forever? This is where infinite loops come into play. The only way to stop these loops is to press the stop button. Take a look at the example below:

 

loop do
    sample :loop_amen
    sleep sample_duration :loop_amen
end

 

This loop will play the amen loop repeatedly forever until you stop it! What do you think will happen if you put some code after the loop? Let’s give it a shot with the following code:

 

loop do
    sample :loop_amen
    sleep sample_duration :loop_amen
end

sample :drum_cymbal_open

 

You should notice that the cymbal sample never plays. This is because the program never exits the loop and the sample is outside of the loop. This is an example of why you need to be careful when using infinite loops. Now you have the power of iteration and loops at your fingertips!

4

⁉️ Conditionals

10 min
Keyboard Guide

Conditionals

 

 

The Code Explained


 

At certain times, you may want your music to pick between multiple different options to add variety to your music. This is where conditionals come in to play. They simply allow your code to check for a certain condition and then make a decision based upon that.

The simplest way to think about this is flipping a coin. If the coin lands on heads you play one sample and if it lands on tails you play a different sample. Let’s look at an example of a conditional that uses the built-in one_in method:

 

loop do
    if one_in(2)
        sample :drum_heavy_kick
    else
        sample :drum_cymbal_closed
    end
    sleep 0.5
end

 

If you run this code you should notice the program picking between the two options and looping forever!


 

Let’s talk about the parts of a conditional statement now.

 

The first part is the if keyword. This lets the computer know that a conditional is starting and then is followed by the condition that needs to be met. Inside of the conditional, you have the code that will be run if the condition is met. You can stop there and add the end keyword if you want or you can use the else keyword to declare what should happen if the condition isn’t met.

Just remember that you still have to have the end keyword after the if-else statement! Finally, I’m going to show you one more trick called a simple if. This will allow you to write an if statement in a much simpler way. Take a look at the example below:

 

use_synth :dsaw

loop do
    play 50, amp: 0.3, release: 2
    play 53, amp: 0.3, release: 2 if one_in(2)
    play 57, amp: 0.3, release: 2 if one_in(3)
    play 60, amp: 0.3, release: 2 if one_in(4)
    sleep 1.5
end

 

This code puts the if statement in line with the note that should play if the condition is met. This code will cause different chords to play based upon differing probabilities! Give it a shot and see what you can come up with!

5

🧵 Threads

15 min
Keyboard Guide

Threads

 

 

The Code Explained


 

Now that you know about loops we can start putting songs together! Imagine having a bassline and a drumbeat playing at the same time. You could weave them together but that quickly becomes confusing. This is where threads come in handy. You can think of threads like branches on a tree. The buffer is the main branch and the main thread. Then, each thread branches off of that. This allows each thread to run simultaneously to each other. If we didn’t use threads, our code would enter a loop and then never exit. Look at the code below for a simple example of threads.

 

in_thread do
    loop do
        sample :drum_heavy_kick
        sleep 1
    end
end

in_thread do
    loop do
        use_synth :fm
	play 40, release: 0.2
	sleep 0.5
    end
end

 

As you can hear in the above example, both loops are playing at the same time. This is because the in_thread keyword creates a new thread every time it is called and they are both set to start at the same time. Without the in_thread keyword, the second loop would never be reached! It is best practice to use in_thread for every thread you want to create even though you don’t have to for the last loop in your sequence.


 

Scope and Inheritance

 

It is important to note that threads isolate settings. This is known as scope and it simply means that settings are only applied to the thread they are set in. Take a look at this example to see how this works:

 

play 50
sleep 1

in_thread do
    use_synth :tb303
    play 50
end

sleep 1
play 50

 

As you can hear in this example, the use_synth keyword changes the note that is inside of that thread! This can be combined to create different melodies in one song. You can have a bassline that uses one synth and another melody that uses a completely different synth.

There is another concept in scope called inheritance and it means that a thread will inherit any settings from it’s parent thread unless otherwise set. Basically, the main thread can pass settings to a child thread but a child thread cannot pass settings to its parent. Take a look at the example below:

 

use_synth :tb303
play 50
sleep 1

in_thread do
    play 55
end

 

As you can see, the use_synth setting is passed down from the main thread into the child thread. Keep this in mind when writing your music.


 

Naming Threads

 

The last thing to know about threads is that you can name them. This may not seem important now but it will definitely come in handy later. I like to give my threads descriptive names so that I can remember exactly what each thread does. Below is an example of how to name threads:

 

in_thread(name: :bass) do
    loop do
        use_synth :prophet
	play :E2
	sleep 0.5
	play :D2
	sleep 0.5
    end
end

in_thread(name: :drums) do
    loop do
	sample :elec_snare
	sleep 1
    end
end

 

🌟  The name of the thread has to be enclosed with parentheses and must have a colon at the beginning of the name.

 

This will allow you to easily keep track of your threads and even see when they are playing if you look in the log pane! The final thing to note about naming threads is that each thread has to have a unique name. If any of the threads have the same name then every thread after the first one will not be created.

6

📋 Functions

10 min
Keyboard Guide

Functions

 

 

The Code Explained


 

When you start to have a lot of code, you may notice that your workspace has gotten a lot messier and you want to tidy up a bit. Thankfully, we can use something called a function to do just that. Functions will allow you to group sections of code and name those sections that can then be called later. Look below to see an example:

 

define :foo do
    play 50
    sleep 1
    play 55
    sleep 2
end

foo

sleep 1

2.times do
    foo
end

 

The code above allows you to name the sequence of code and then run it later.  Here we defined a function called :foo! This function tells Sonic Pi to play the note 50, sleep for 1  beat, play note 55, then sleep for 2 beats. So instead of typing all those instructions out, you can call the :foo function and it'll remember it for the next time!

You can name your function anything you want but it is best to be descriptive.

 

🌟  Remember, that all functions have to start with a colon. Once you've defined it, when you are ready to call the function all you have to do is type its name and it will run!

 

Another nice thing about functions is that they can be remembered across runs. This means that after you run it once you can delete the function but it can still be called by typing the name. Give it a try by deleting the function in your code! This function can only be used in this buffer and during this session but it can be used as many times as you want.

7

💌 Variables

10 min
Keyboard Guide

Variables

 

 

The Code Explained


 

Now we will take a quick detour away from functions to discuss a concept known as variables. Variables are similar to functions in that they are containers for data. You can use variables to assign a name to a piece of data then when you want to call it you simply type the name. Take a look at the example below:

 

sample_name = :loop_amen
loop_amen_duration = 1.7533
play sample_name
sleep loop_amen_duration
play sample_name

 

We have assigned values to each of these variables and then we access those values by calling the variable! In this situation it isn’t very helpful but this is just an example of what you can do.

 

🌟  Name a variable by typing your_variable_name = and setting it to whatever you want (a particular synth, loop, option, number etc...). Remember that sample names begin with a : (colon)!

 

It is important to note that you can only access a variable inside of the thread you declare it in. This goes back to the idea of scope and inheritance that we learned about earlier.

8

📏 Parameterized Functions

10 min
Keyboard Guide

Parameterized Functions

 

 

The Code Explained


 

This is obviously a simple example but if you run this code you will notice that the number is passed into the function using the variable n and is then played.

 

🌟  Parameters are variables that are passed through functions where they do something with those given variables.

 

In the video above, the function :chord_player is called multiple times using different parameters (:E4, 2, :G4, 5) to create different tunes using minimal code.

To declare a parameter, you must put its name inside of the two vertical lines that we call goal posts. This will then allow you to put a value after calling your function that will then be passed into the function. Let’s take a look at something a little more complicated now:

 

define :chord_player do |root, repeats|
    repeats.times do
        play chord(root, :minor), release: 0.3
        sleep 0.5
    end
end

chord_player :e3, 2
sleep 0.5
chord_player :a3, 3

 

As you can see, this function takes two parameters. One is a note while the other is a note.

 

🌟  |root, repeats| is the order of your parameters. When you type :E4, 2 you are saying |:E4, 2| as :E4 lines up with root and 2 lines up with repeats.

 

This particular function will play a chord based around that note and play it a certain number of times. Don’t worry if you don’t understand the play chord code yet, we will learn about it tomorrow! Now you should know the basics of functions and variables!

9

🤩 Enhancing Our Project

5 min
Keyboard Guide

Enhancing Our Project

 


 

Upgraded Jingle

 

Now that you have a knowledge of loops and threads you can revisit your jingle and make it even better! Maybe now you want to add a drum section to your song or even a bassline using threads! You could even make your code neater by using loops or have it play infinitely! It’s all new power at your fingertips!


 

Upgraded Morse Code

 

With the power of functions, you can clean up your Morse code! Consider putting code for certain letters inside a function! This way instead of typing out the code every time you just have to type the name of the function! This can be combined with loops to shorten your code or to have your message play repeatedly forever!

10

👨🏿‍💻 More Coding + Other Projects

5 min

CONGRATS, YOU'RE DONE! WHAT'S NEXT?


 

Want to Code in Another Language?

 

Check out our Python Game Design: Rock, Paper, Scissors project!

 

 

Curious About Other Skills?

 

Visit our Browse page and discover even more STEM skills!

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.