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
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!
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.
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!