Skip to Content

How can I loop music with code in Sonic Pi?

Think About

  • Why is it useful to repeat musical patterns?
  • How can you repeat musical patterns with code? 

Loop Music With Sonic Pi

  1. Try out tutorial 5.2  in Sonic Pi to learn how to loop blocks of code to make music.
  2. Once you’ve tried out this tutorial, try looping blocks of code to create a repeating melody, harmony, or beat.

Need an example to repeat?

  • Use one of the examples in the “Help” section of Sonic Pi
  • OR
  • Watch from 6:40 – 7:30  to learn how to loop music with code using Hot Cross Buns

OR

  • Add loops to your own remix of music coded by Jared O’Leary by copying the code below and pasting it into Sonic Pi
#========================#
# Coded by Jared O’Leary #
#   www.JaredOLeary.com  #
#========================#

# This program creates a simple, but random, beat
loop do
  # First it plays a bass drum along with four hi hat sounds (:drum_cymbal)
  sample :drum_heavy_kick
  4.times do
    # The if/else conditionals will randomly pick either the first sample or the second if the condition is not met
    # The one_in(4) means that the first sample will only occur if the computer rolls a four-sided dice and gets a one
    if one_in(4)
      sample :drum_cymbal_open, amp: 0.45, finish: 0.05
    else
      sample :drum_cymbal_closed, amp: 0.25
    end
    sleep 0.125
  end
  # The second half of this code plays a snare and plays one of the two cymbal sounds again
  sample :elec_snare
  4.times do
    if one_in(4)
      # What does finish: do to the sample?
      sample :drum_cymbal_open, amp: 0.45, finish: 0.05
    else
      sample :drum_cymbal_closed, amp: 0.25
    end
    sleep 0.125
  end
end

Try meeting these challenges:

  • Can you use loops to make a song that never ends?
  • Can you make a repeating song that doesn’t get boring?
  • Can you use loops to make a beat with drums, melody, and harmony?
  • Can you make a bunch of loops that sound almost the same but have little differences?

If you are using the LRNG platform, go back, find out what to submit, and complete the XP.

If you are not using the LRNG platform, return to: How can I loop music with code?