How to Use Shuffle on Your Raspberry Pi
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:
play_pattern_timed [:c4, :d4, :e4, :f4, :g4, :a4, :c5].shuffle, ↩ [0.5, 0.5, 1, 0.5, 0.5, 1, 2]
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.