# Lesson 15 # Functions Lesson. In this lesson, # you will learn how to define and # use functions in Sonic Pi. # General Instructions: # # This lesson contains one example and # one exercise (A). # # 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. # # You may have noticed that creating # interesting musical patterns in Sonic # Pi might involve writing repetitive # lines of code. You can "package" a # block of code by defining it as a function. # Example 1: Musical Functions. comment do define :twinkle_a do melody_a = [:C4, :C4, :G4, :G4, :A4, :A4, :G4] index = 0 count = melody_a.length count.times do play melody_a[index] sleep 1 index += 1 end sleep 1 end define :twinkle_b do melody_b = [:F4, :F4, :E4, :E4, :D4, :D4, :C4] index = 0 count = melody_b.length count.times do play melody_b[index] sleep 1 index += 1 end sleep 1 end define :twinkle_c do melody_c = [:G4, :G4, :F4, :F4, :E4, :E4, :D4] index = 0 count = melody_c.length count.times do play melody_c[index] sleep 1 index += 1 end sleep 1 end use_bpm 120 twinkle_a twinkle_b twinkle_c twinkle_c twinkle_a twinkle_b end # Exercise A: # Define a new function named "twinkle_play" # that wraps the calls to twinkle_a, # twinkle_b, and twinkle_c in a single function. # Call twinkle_play from inside a # thread, and then call it outside (below) # the thread after a delay of four beats. Then # do a version with a delay of eight beats.