Raspberry Pi For Dummies
Book image
Explore Book Buy On Amazon
Your Raspberry Pi can shuffle your music if you want to play random songs. Take a look below. The bracketed sections are lists, similar to lists in Python. You can add different instructions (or methods) to the lists to change the order of the items in them. For example, try this, using the reverse method:

play_pattern_timed [:c4, :e4, :g4, :c5], [0.5, 0.5, 1]

play_pattern_timed [:c4, :e4, :g4, :c5].reverse, [0.5, 0.5, 1]

You’ll hear the notes of the fanfare played forward and then backward, but with the same timing each time. You can use the shuffle method, which changes the order of the items in a list, to hear a random tune. Try this:

play_pattern_timed [:c4, :d4, :e4, :f4, :g4, :a4, :c5].shuffle, ↩ [0.5, 0.5, 1, 0.5, 0.5, 1]

A simple rhythm was used there: two short notes and then a long note. It’s a cheery melody, but it’s a bit short, so get Sonic Pi to repeat it. Here’s how:

4.times do

play_pattern_timed [:c4, :d4, :e4, :f4, :g4, :a4, :c5].shuffle, ↩ [0.5, 0.5, 1, 0.5, 0.5, 1, 2]

end

play :c4

This example wraps the tune playing code in a loop that repeats it four times. The start of the loop is 4.times do, and the end of the repeating section is marked, appropriately enough, with the word end. Sonic Pi automatically indents your musical code by two spaces to show it’s the part that is to be repeated. If you want to repeat more or less than four times, change the number 4 at the start.

There are some other changes here, too: First, a timing value was added for the last note in the sequence. It’s the 2 that has sneaked inside the last square bracket. A final note has also been added, :c4. Whatever randomness happens in the rest of the tune, this sequence of notes always sounds good when it ends on a C, because all the notes in the sequence are from the C major scale.

About This Article

This article is from the book:

About the book authors:

Sean McManus is an expert technology and business author. His previous books include Mission Python, Coder Academy, and Cool Scratch Projects in Easy Steps.

Mike Cook is a former professor in physics at Manchester Metropolitan University. His other books include Raspberry Pi Projects and Raspberry Pi Projects For Dummies.

Sean McManus is an expert technology and business author. His previous books include Mission Python, Coder Academy, and Cool Scratch Projects in Easy Steps.

Mike Cook is a former professor in physics at Manchester Metropolitan University. His other books include Raspberry Pi Projects and Raspberry Pi Projects For Dummies.

This article can be found in the category: