# Lesson 19 # Randomization Lesson. In this lesson, # you will learn how to introduce an # element of chance or randomization # into your Sonic Pi code. # General Instructions: # # This lesson contains two examples and # three exercises (A, B, C). # # To listen to an example, change "comment" # to "uncomment" on the "comment do" line, # then click the "Run" menu command at the # top of the Sonic Pi editor window. # When you are done with the example, turn # it off by changing "uncomment" back to # "comment," and move on to the next section # of the lesson. # # Example 1: Randomizing arrays. comment do in_thread do loop do play chord(:C, :minor7).choose sleep 0.5 end end in_thread do loop do play scale(:C, :minor_pentatonic).tick sleep 0.5 end end melody = [:C5, :Eb5, :G5, :Ab5, :B4, :G5, :Gb5, :F5, :E5, :Eb5, :D4, :C5, :B4, :C5, :F5, :Eb5, :D5, :C5] loop do play melody.choose sleep 0.25 end end # Exercise A: # The choose command selects a random element # from a ring or an array. Sonic Pi has # built-in chord and scale arrays which work # with the choose command. Change Example 1 # in the following ways: # 1) Change the chord root and type in the # first thread. # 2) Change to different kinds of scales in the # Sonic Pi system and change the tonic note. # 3) Change the notes of the melody array. # # Example 2: Randomizing numbers # There are several ways to randomize note # selection in Sonic Pi using random numbers. # The rrand command will select a random real # number within a given range. This works well # for selecting pitches directly. The rrand_i # command selects whole numbers (integers), # which is a good way to select an index # into an array. comment do in_thread do loop do play rrand(35.6, 120.9) sleep 0.25 end end melody = [:C5, :Eb5, :G5, :Ab5, :B4, :G5, :Gb5, :F5, :E5, :Eb5, :D4, :C5, :B4, :C5, :F5, :Eb5, :D5, :C5] loop do index = rrand_i(0, melody.length - 1) play melody[index] sleep 0.5 end end # Exercise B: # Change Example 2 in the following ways: # 1) Change the melody array to a ring, and # make the lower value of the range for the # index a negative number (< 0). # 2) Restrict the range for notes in the # rrand statement in the first thread # to less than one whole number. # 3) Experiment with random sleep times # for both threads. # # Exercise C: # Create a loop that plays samples with # changing rates. Use the rrand command to # select the sample rate. Try using both # negative and positive numbers for the # sample rate.