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!