9.1 Live Coding Fundamentals
Now we’ve learned enough to really start having some fun. In this
section we’ll draw from all the previous sections and show you how you
can start making your music compositions live and turning them into a
performance. For that we’ll need 3 main ingredients:
- An ability to write code that makes sounds - CHECK!
- An ability to write functions - CHECK!
- An ability to use (named) threads - CHECK!
Alrighty, let’s get started. Let’s live code our first sounds. We first
need a function containing the code we want to play. Let’s start
simple. We also want to loop calls to that function in a thread:
If that looks a little too complicated to you, go back and re-read the
sections on functions and threads. It’s not too complicated if you’ve
already wrapped your head around these things.
What we have here is a function definition which just plays note 50 and
sleeps for a beat. We then define a named thread called :looper
which just loops around calling my_sound repeatedly.
If you run this code, you’ll hear note 50 repeating again and again…
Changing it up
Now, this is where the fun starts. Whilst the code is still running
change 50 to another number, say 55, then press the Run button
again. Woah! It changed! Live!
It didn’t add a new layer because we’re using named threads which only
allow one thread for each name. Also, the sound changed because we
redefined the function. We gave :my_sound a new definition. When the
:looper thread looped around it simply called the new definition.
Try changing it again, change the note, change the sleep time. How about
adding a use_synth statement? For example, change it to:
Now it sounds pretty interesting, but we can spice it up
further. Instead of playing the same note again and again, try playing
a chord:
How about playing random notes from the chord:
Or using a random cutoff value:
Finally, add some drums:
Now things are getting exciting!
However, before you jump up and start live coding with functions and
threads, stop what you’re doing and read the next section on
live_loop which will change the way you code in Sonic Pi forever…