Any real piece of music is going to contain more than one note. Type the following code in the Code Editor and click on Run. What do you hear?
play 60 play 65 play 72
That might not have sounded the way you expected! All the notes played at the same time. Sonic Pi will play every note it sees until it reaches a sleep
command, upon which it waits for a certain amount of time and then continues. This is useful when we want to play multiple notes at once, but to create a tune, we need them all to be separate. Put a sleep
command after each play
command, like this:
play 60 sleep 1 play 65 sleep 1 play 72 sleep 1
That's better! All the notes now play one after another. The number after the sleep
command is the number of seconds to wait before playing the next note (or notes). Again, we can use any number we like, and the number can be different for each sleep
command.
Now, music is largely based on repetition, so let's learn how to create loops in Sonic Pi. It's very simple—add a loop do
and an end
around the code that we want to repeat, like this:
loop do play 60 sleep 1 play 65 sleep 1 play 72 sleep 1 end
The do
and end
tell Sonic Pi which lines of code are in the code block and the loop
tells it what should be done with the block. In this case, we want the code to repeat forever. We don't need to indent the code within the block (as we do in Python), but it helps make the code more readable, especially when we have complex structures such as loops within loops. At any time, you can click on the Align button at the top of the window and it will choose what it thinks is the best indentation for your code.
If you like to repeat the code a fixed number of times, replace loop
with any number followed by .times
. For example, the first line can be 10.times do
if you want to repeat the code ten times.
Finally, let's tweak our code to create a random tune. The first thing we're going to do is put all the notes we want to play into a list. We can do this in exactly the same way as we did in Python. Here's a list that contains the three notes from the previous example:
[60, 65, 72]
See how we separate each number in the list with commas, and we wrap the whole thing with square brackets. You can change any of these numbers or add new ones if you like. To get a random number from our list, we will use the choose
function that Sonic Pi provides. Here is a new code block to put inside our loop:
play choose([60, 65, 72]) sleep 1
If you run this code, you should hear a sequence of random notes taken from the list.
3.135.196.103