Sonic Pi

1 Samples and Loops

Learn It

  • As well as playing single notes, we can also play pre-recorded sounds using Sonic Pi.
  • These are called samples and there are plenty to choose from.

Code It

  • Let's play a sample.
sample :drum_snare_hard

Learn It

  • The sample function takes the name of the sample as an argument, but it can take other argument as well.
  • We can change the length of time it plays for using rate
sample :drum_snare_hard, rate: 0.5
  • This doubles the time the sample plays for.
  • We can also change the volume of the sample.
sample :drum_snare_hard, rate: 0.5, amp: 3

Try It

  • Play around with rate and amp
  • Can you make a sound like thunder?
  • Can you make a sound like a gentle tap on a window?

Try It

  • Have a play around with some other samples.
  • When you start typing sample : into the workspace you'll be presented with all the sample available.
  • Have a go at these:
    • sample :ambi_choir
    • sample :ambi_glass_hum
    • sample :guit_e_fifths
  • Change the amp and rate of the samples you choose to see how they are altered.

Learn It

  • In music, drumming tends to be fairly repetitive.
  • We'll rarely want to play just a single drum beat. More likely, we'll want to play the beat 50 times or more.
  • We could do this by simply repeating the same function calls, over and over again.
sample :drum_snare_hard
sleep 0.5
sample :drum_snare_hard
sleep 0.5
sample :drum_snare_hard
sleep 0.5
sample :drum_snare_hard
  • But as you've learned previously, when coding, if we want to do something multiple times, it's easiest to use a loop.

Code It

  • Try the following.
4.times do
    sample :drum_snare_hard
    sleep 0.5
end
  • The indentation is optional, but helps you see which elements of the code are within the loop.
  • Play this and see what happens.

Try It

  • Now try playing with the amp and rate of the sample along with the length of sleep

Learn It

  • We can also nest loops within loops.
4.times do
    sample :drum_snare_hard, rate: 0.5, amp: 2
    3.times do
        sample :drum_snare_hard, rate: 1.5
    end
end

Badge It

  • Create a cool bass line using samples and loops.
  • Make sure you're experimenting with different samples and their rate and amp arguments.