Hardware Reference
In-Depth Information
FIGURE 7-10
Using conditionals and random in Sonic Pi
Using “rand” to Play Random Notes
You can use
rand
in other interesting ways outside of a conditional too. For example,
you could use it to play a random note in a sequence.
Underneath the conditional sequence, after the final end line, type the following:
3.times do
play 60 + rand(10)
sleep 0.5
end
The first line is the start of the repeating loop. Everything after
do
and before
end
will be played three times. The next line uses a calculation to determine what note it
will play. The code
play 60 + rand(10)
will play a random note between 60 and 69
because you are adding a random number between 0 and 10 to 60 to make a random
note each time; for example, 61, 68, 63. Changing the value of
play 60
sets the low-
est note, whilst changing the value of
rand(10)
changes the range of the highest note.
This will make the music sound more interesting, especially if it is inside a loop, as
each time it is played a different note could be heard between the MIDI note numbers
you specify.