We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

Learn to Make Music. With Ruby.

00:00

Formal Metadata

Title
Learn to Make Music. With Ruby.
Title of Series
Number of Parts
66
Author
Contributors
License
CC Attribution 3.0 Unported:
You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal purpose as long as the work is attributed to the author in the manner specified by the author or licensor.
Identifiers
Publisher
Release Date
Language
Producer
Production PlaceSan Antonio

Content Metadata

Subject Area
Genre
Abstract
If you can write code, you can make music. And in this talk, and you'll see exactly how. We'll take a look at Sonic Pi, a powerful, multi-platform app that uses a Ruby DSL to create just about any kind of music you can think of. And if you've never made a note of music in your life, fear not: you'll also get a crash course in music composition and learn how the elements of rhythm, melody, and harmony work together to make a cohesive whole. Bring your laptop and headphones: this will be very hands-on, and you'll be making your first track before we even get to questions!
CodeSupersonic speedPiPhysical systemAxiom of choiceSoftwareGoodness of fitMusical ensembleOpen sourceSupersonic speedCodeMultiplication signInternetworkingProgrammer (hardware)OctahedronDatabaseNeuroinformatikCartesian coordinate systemWindowComputer animation
CodePhysical systemFormal languageSupersonic speedMusical ensembleNeuroinformatikPiMereologyPlastikkarteCodeBetti numberProgrammschleifeGame controller
Boom (sailing)Supersonic speedCoding theorySample (statistics)Bit rateLink (knot theory)Loop (music)GodProcess (computing)Moment (mathematics)TouchscreenProjective planeRight angleCodeNeuroinformatikMultiplication signSource code
Supersonic speedPoint (geometry)Musical ensembleInheritance (object-oriented programming)NeuroinformatikPiVideo game
Line (geometry)Musical ensembleNumberMoment (mathematics)BitSlide ruleSingle-precision floating-point formatPhysical system
PiMusical ensembleDifferent (Kate Ryan album)Element (mathematics)Programmer (hardware)Supersonic speedDisk read-and-write headWordLecture/Conference
Virtual machineScale (map)Sample (statistics)Thread (computing)Range (statistics)Bit rateInfinite conjugacy class propertyHill differential equationRevision controlComputer filePiRadical (chemistry)Series (mathematics)Type theorySupersonic speedWindowSingle-precision floating-point formatMusical ensembleMereologyArmMathematical singularityPoint (geometry)Arithmetic meanBookmark (World Wide Web)Graph coloringSoftwareSource codeLecture/Conference
Thread (computing)Sample (statistics)NumberType theoryComputer configurationBitOctaveEquivalence relationMultiplication signVolume (thermodynamics)Metropolitan area networkIntegerRight angleLecture/Conference
Scale (map)Physical systemNumberSpacetimeSynchronizationMusical ensembleMultiplication signLecture/Conference
Supersonic speedMusical ensemblePulse (signal processing)Distance2 (number)NumberBeat (acoustics)Term (mathematics)BitApproximation
NumberOrder (biology)Disk read-and-write headMusical ensemblePositional notationLoop (music)Parameter (computer programming)RandomizationBitMultiplication signMetropolitan area network
Loop (music)Random number generationUser interfaceMobile appWeb applicationAxiom of choiceNumberScaling (geometry)Graph coloringMultiplication signConsistencyCohesion (computer science)Range (statistics)Interface (computing)Musical ensembleIntegerSubsetFunctional (mathematics)BitField (computer science)Data managementProgrammer (hardware)Lecture/ConferenceComputer animation
Scaling (geometry)Musical ensembleGraph coloringMultiplication signKey (cryptography)
Loop (music)Computer iconScale (map)Graph coloringKritischer ExponentScaling (geometry)Electronic mailing listSinc functionSupersonic speedMultiplication signComputer animation
Scale (map)Loop (music)Chromatisches PolynomBitElectronic mailing listScaling (geometry)MathematicsMultiplication signChord (peer-to-peer)Supersonic speedMoment (mathematics)Expert systemRight angleFunctional (mathematics)Instance (computer science)Lecture/ConferenceComputer animation
Chord (peer-to-peer)Scaling (geometry)Functional (mathematics)Chord (peer-to-peer)Positional notationWordElectronic mailing listMathematicsOrder (biology)Data miningCheat <Computerspiel>Lecture/ConferenceComputer animation
Chord (peer-to-peer)Chord (peer-to-peer)1 (number)Multiplication signBitMathematicsMusical ensembleHacker (term)Lecture/Conference
Musical ensembleCore dumpTunisChord (peer-to-peer)
Chord (peer-to-peer)Loop (music)WhiteboardVariable (mathematics)Chord (peer-to-peer)Multiplication signCodeBeat (acoustics)Lecture/Conference
Loop (music)Chord (peer-to-peer)BitChord (peer-to-peer)
Loop (music)Chord (peer-to-peer)12 (number)Chord (peer-to-peer)Electronic mailing listProgrammer (hardware)Shift operatorBitMathematicsComputer animation
Loop (music)Link (knot theory)Data structureElement (mathematics)Multiplication signIterationElectronic mailing listRing (mathematics)Subject indexingHydraulic jumpPiCircleGoodness of fitSupersonic speedPointer (computer programming)Chord (peer-to-peer)Functional (mathematics)Inheritance (object-oriented programming)
Link (knot theory)Loop (music)Sampling (statistics)Musical ensembleBitMultiplication signFigurate numberMiniDiscDemosceneTheory of relativityComputer fileInheritance (object-oriented programming)Level (video gaming)NumberContext awarenessPiDevice driverHost Identity ProtocolForm (programming)MathematicsWaveformSupersonic speedInterior (topology)
Sample (statistics)Bit rateRow (database)Bit rateSampling (statistics)LengthNegative numberMultiplication signLecture/Conference
Loop (music)Sample (statistics)BitBeat (acoustics)Pattern languageLecture/Conference
Sample (statistics)Loop (music)TheoremDrum memoryMultiplication signSampling (statistics)Supersonic speedSocial classMusical ensembleCodeLine (geometry)Lecture/Conference
Sample (statistics)Loop (music)Electronic mailing listSampling (statistics)Loop (music)WordDrum memoryBeat (acoustics)Supersonic speedInformationComputer fileRow (database)QuicksortLengthMusical ensembleForcing (mathematics)Stiff equation
Sample (statistics)Loop (music)Multiplication signSampling (statistics)LiquidLecture/Conference
12 (number)Loop (music)Sample (statistics)Chord (peer-to-peer)Multiplication signThread (computing)CodeLoop (music)Endliche ModelltheorieGreatest elementInfinityMereologyComputer programmingFerry CorstenBlock (periodic table)Supersonic speedSource code
Sample (statistics)Loop (music)Multiplication signSampling (statistics)Line (geometry)Computer configurationForestBit rateSynchronizationBeat (acoustics)Musical ensembleCodeLength
Loop (music)Sample (statistics)Scale (map)Logic synthesisDefault (computer science)Lecture/Conference
12 (number)Loop (music)Scale (map)Electronic mailing listBEEPComputer configurationFunctional (mathematics)
Loop (music)Scale (map)Limit (category theory)Multiplication signFrequencyVolume (thermodynamics)Functional (mathematics)Computer configurationLevel (video gaming)MereologyFilm editing
Loop (music)Scale (map)Sample (statistics)FrequencyRandomizationOpen setBitProgrammschleifeSound effectQuicksortMathematicsMusical ensembleSupersonic speedBEEPLecture/Conference
Sample (statistics)Parameter (computer programming)Sound effectCodePower (physics)Block (periodic table)Lecture/Conference
Sample (statistics)ECosMultiplication signParameter (computer programming)CodeSystem callBlock (periodic table)BefehlsprozessorSound effectLecture/Conference
Sample (statistics)Loop (music)CodeMultiplication signECosPhysical systemBitMereologyBlock (periodic table)Mixed realityChord (peer-to-peer)
Random numberThread (computing)Loop (music)Sample (statistics)Optical disc drivePulse (signal processing)12 (number)TunisGoodness of fitBitMusical ensembleDifferent (Kate Ryan album)RandomizationMultiplication signCASE <Informatik>Thread (computing)Mathematics
Sample (statistics)Loop (music)Thread (computing)Loop (music)Thread (computing)QuicksortBEEPDrum memorySystem call
Thread (computing)Sample (statistics)BEEPAreaChord (peer-to-peer)MathematicsMultiplication signINTEGRALLoop (music)Level (video gaming)Lecture/ConferenceComputer animation
AreaThread (computing)Sample (statistics)BEEPState transition systemChord (peer-to-peer)Computer animation
Thread (computing)AreaSample (statistics)Greatest elementArtificial lifeComputer clusterMusical ensembleDataflowGroup actionProgrammschleifeSet (mathematics)
Supersonic speedInstallation artMultiplication signRule of inferenceBuildingMatrix (mathematics)MereologyHypermediaProgrammschleifeFile formatPhysical systemSampling (statistics)Musical ensembleTwitterGroup actionFunctional (mathematics)Sheaf (mathematics)Pattern languageSource codeWaveComputer filePiRange (statistics)Line (geometry)Supersonic speedInternetworkingType theorySoftware testingInformationRow (database)EmailWritingDistanceAdventure gamePoint (geometry)1 (number)Data conversionOnline helpMIDIInheritance (object-oriented programming)Installation artMP3MiniDiscCodeRight angleComputer animation
Transcript: English(auto-generated)
Okay, good morning. Thank you all for coming. We know you have a choice in conference talks,
and we appreciate you flying Sonic Pi Airlines. So today I'd like to talk about making music with Ruby, and specifically using a software system called Sonic Pi. Sonic Pi was created by a guy named Sam Aaron, who's a programmer working over in the UK. And one of his primary motivations when he made it
was to try to give people a creative experience with code. That sounds a little funny, because a lot of times people think of code as just something for making very serious business applications, or big crazy government databases, or sharing pictures of your food on the internet. These are all very important, but for Sam, code could be a lot more than that.
It could be a vehicle for self-expression and creativity. And he wanted everyone to have an experience of that, including and especially people who had never coded before. So he tried to make Sonic Pi as accessible as possible. It's completely free and open source. It runs on Mac, Windows, and Linux, and it was specifically designed
to run on the Raspberry Pi computer, which we saw a little bit of in the last talk if you were here. This is about a credit card-sized computer. It costs about $35. You plug in a USB keyboard and mouse, plug it into a monitor or even TV, and you're ready to go. Sonic Pi was written in Ruby, naturally,
and the language it uses for creating the music is a very elegant and very approachable Ruby DSL. And after seeing Betsy's talk yesterday, I'm not even sure it's a DSL. For the most part, it's straight-up Ruby with a really, really nice API.
So it's easy for just about anybody to get started with it. And in fact, Sam collaborated with a schoolteacher in the UK to develop a curriculum for bringing Sonic Pi into primary schools and teach 10-year-old kids the basics of coding. But the real miracle of the system for me is that on the one hand, it's simple enough for 10-year-old kids
to play around with and do bleeps and bloops and all kinds of interesting things. But it's also sophisticated enough that Sam and other folks have taken it into live performance in nightclubs, coding up there while people are dancing, dancing to code. Think about that for a minute. So here's an excerpt of one of his performances
if the gods of the wireless are smiling on us at this moment. So it's a little dark, but there's a camera on Sam in the upper right-hand corner having fun. Oh, slight delay.
And he usually has the code projected in a screen behind him so people can see what's going on. And we're getting a good look at the loading. Well, it gives you a taste of it anyway.
By the way, that's running on the Raspberry Pi. So you don't even necessarily need, thank you to our sponsor, you don't even necessarily need a super powerful computer to run this. So all this is fantastic, and it's a really cool system. But one of the things that got me really excited about it
when I first found out about it is that it's a nice way not only to get people started coding, but to get people started making music. I've been a musician for most of my life, and I earned my living musician for a few years until I turned bad and became a programmer. My poor parents still haven't gotten over that. And I often meet people who say
that they would like to learn to make music, but they don't because it seems too daunting or too expensive, or it would just take too long for them to get to the point where they could make something interesting. But Sonic Pi provides a really nice friendly on-ramp to this, and you can get something kind of fun going up quickly.
So when I meet people like this now, I can say, try out Sonic Pi. So in this talk, I'm gonna give you a quick music lesson with Sonic Pi and hopefully convince you to give it a try yourself. Now, we've seen this slide a lot, and I'm sorry to say there's gonna be a little bit of this in this talk. There will be moments where it'll seem perfectly clear,
and then it's gonna seem like I take some weird logical leap, put in a couple numbers, and I have an owl. And I apologize for that. So if you don't grasp every single aspect of it, don't worry about it. Obviously, I can't turn you all into musical masters in 30 minutes or whatever remains. But what I hope to do is just give you a few things to start,
a few ideas that you can approach the system with, and just give you a little nudge across the starting line so that hopefully you can take it and run with it yourself. So with that, let's talk about music. Music can be a little daunting if you've never worked with it before.
It seems very vast. It seems very rich, and it's also very, very abstract. So how do you even get started? How do you approach it? How do you start to wrap your head around it? Well, as programmers, we learned that if you have a big, complex, seemingly insurmountable problem, the way to attack it is to break it down into smaller, more manageable problems.
And it turns out you can do that with music, too. One way to think of music is that it consists of four different elements, melody, harmony, rhythm, and timbre. The first three of these you probably have at least an instinctive sense of. Timbre you may not have heard before. But really, it just talks about the sound of the instruments producing the music.
So if you think about the difference between a flute and a guitar and a kazoo, the difference between those three is what timbre is all about. So I'll go through each one of these and show how they manifest in Sonic Pi, and hopefully give you enough to go on. So let's switch over to Sonic Pi.
I also want to point out, this is what Sonic Pi looks like when you first install it and run it. You download it as a binary, and you're up and ready. You don't need to worry about installing Ruby. You don't have to get your Bundler file just right. You don't have to install gems. You don't have to worry about your version of Mac
has lib08.6 of whatever the hell is broken this week. You're ready to go right away. You don't even have to open a terminal. This main window is where you enter the text, and then you click the Run button to start the music. The Stop button stops it, and kind of that's all you need to know to get started.
There are lots of other things you can do, adjusting the size, adjusting the colors, saving your work, but really just type in text and go. So for beginners, it's a really, really nice experience to start with. So let's start with melody. What is a melody? A melody is really just a series
of single notes played in succession. That's all a melody is, and it's usually the most forward-facing part of a piece of music. So if you're driving down the road, you've got your iPod on, and you're singing along to your favorite song, chances are you're singing the melody, because that's the thing that's most forward, unless you're strange like me, and you're singing anything but the melody,
but that's my own problem. So how do we play a melody in Sonic Pi? Well, let's start by playing a single note. To do that, we use the play command, and see, I love this software already. The first thing I do is type play. That makes me happy. So what do we pass to the play? The note that we want to play. How do we do that? Well, with a number.
And we're off and running. Now what does this number mean? Well, it's the equivalent of middle C on the piano, if that means anything to you, but the truth is you don't really need to know what it means. All you really need to know is that with higher numbers, you get a higher pitch.
With lower numbers, you get a lower pitch. And as you increment one integer at a time, that is exactly the equivalent of walking up to a piano and just going up all the notes one by one, or going fret by fret on a guitar. Now you can also do some things
that you can't do on a piano. That will work. That's a note that's not on the piano. That note is definitely not on the piano, but you can do it. Now if you have some musical background and you know the names of notes, you can actually work with those too. This is another way of saying the same thing.
It's the note C in the fourth octave. For some people that's easier, but you can also just play with the numbers. Play takes a few options. You can set the release to make it sustain longer. You can change the attack to make it swell up a little bit so it's not full volume right away.
And you can change the volume. But let's keep it simple at first. We'll just work with this. And we want to make a melody. So let's put a few notes, one after the other, and we'll just use even numbers for now, see what that sounds like.
And we hit play. Okay, that's not quite what we had in mind. What happened there? Well, Sonic Pi has a very complicated system of timing underneath it because it wants to keep all the pieces of your music in sync. And we weren't very specific here. We didn't say how much space should happen between each note in our melody. Remember, it's one after the other.
So we need to insert some pauses in here to actually make it sound like a melody. And how do we do pauses? Same way we do it in Ruby, with the sleep command. And now we're really off and running.
Sleep in Sonic Pi works a little bit differently than sleep in Ruby. In Ruby, the number you pass is the number of seconds to pause, and it's approximate. In Sonic Pi, the number you're passing in is the number of beats between each note. It's not apparent right away, but when Sonic Pi is playing the music, it's got a clock that it's syncing everything to.
There's a pulse going on in the background. And in music, we express this kind of pulse as tempo, and we express it in terms of beats per minute, or BPM. It's a term you may have heard. So by default, Sonic Pi will go at 60 BPM, but we can crank it up if we want to using the use BPM command.
That's faster, and that's slower. We can also speed things up by making our sleeps a little bit faster. And we can play around with the rhythm that way. Now this may not seem like much,
but with these two commands that we've just learned in the first few minutes here, you can now play any piece of music that's ever been written by anybody. It's anything that you can express in notation you can do with plays and sleeps. It's just a matter of getting in the right order. But that begs the question, well, how do you know what numbers to put in?
And if you're a beginner, obviously you're not going to know that. So how do you build a melody if you don't know what numbers to put in? Well, Sonic Pi can help you by introducing a little bit of randomness. And by shaping the parameters of the randomness, you can play around with the sound that comes out and get a little head start and then see what you like.
So let's do a loop so we can get a bunch of notes at the same time. And we'll do a sleep and an end, make it pretty. Now instead of play, we want to get a nice random number. Now we could do this.
And this is a function that will give us a random integer between 60 and 90. So it's range rand integer. And you give it two numbers, it'll give you a random integer between those two. We could try that, but it's probably going to sound a little weird.
A little bit too abstract. There's a reason for that. It turns out that in most of the music that we hear most of the time, the composers aren't working with all of the available notes at the same time. At any given time, you're probably just hearing a subset of the available notes. And we call that subset a scale.
And a scale is a lot like a color palette. When you're designing a web app or a mobile app and you start putting the user interface together, you don't just start grabbing any old color willy-nilly and putting it all over the place. I mean, you do if you're a programmer. But probably not if you're a designer. If you're a designer, you take some time in advance and think through what the color palette is going to be.
You say, okay, we're going to use these four or five colors. This will be the main one. This will be the secondary one. And by making those choices and limiting the palette, the whole interface has a sense of cohesion and a sense of consistency to it. Scales are a lot like that. By reducing the number of notes that we use, everything sounds a little more coherent.
So here's a piano. And some of these scales you already know, whether you know it or not. So if I start on this note here and just go up the white keys, it probably sounds familiar. That's called a major scale. Anybody remember Julie Andrews in The Sound of Music
teaching the kids to sing Do Re Mi, all that? She was teaching them a major scale. There's also the minor scale. It has kind of a darker quality to it. There's also the whole tone scale. Which has kind of a dreamy quality to it. You use this in a movie if you're doing a flashback, right?
And remember it like it was yesterday, right? So all of these different scales have different, like color palettes, have different feelings to them, have different emotional qualities. So you don't necessarily need to know what they are. You can just listen to them and see which one you like. So how do we make a scale? Well, Sonic Pi makes that easy too.
There's a scale function. You pass it the note you want to start with. We'll start with 60 because that's been pretty good to us. And then autocomplete helpfully pops up with all of the scales that Sonic Pi knows about. As you can see, there are quite a lot. I don't even know what most of these are. And you don't need to know either.
You can look them up. You can find out how they work, how they're constructed from which whole steps and which half steps. But really you don't need to know that. You can just listen to them. So let's try the major scale since that's the one we just listened to. And we're not quite done yet because the scale function returns a list, just like an array of notes. And if I pass a list of notes to play,
it helpfully thinks that I want to play all of them at the same time, which I don't really want to do. So we're gonna ask it to choose one at random, and we can do that by calling choose on the returned list.
We've got a nice little melody happening. But let's change up the scale, and I'm gonna speed up the notes so we can hear it a little bit more. What's this one? Or we can skip down whatever this one is.
So this is all you need to do. You can just sit there and listen to them and say, oh, yeah, I like that one, I like that one, I don't like that one. And pay attention to your body. That will tell you when you found something interesting. If you're clicking through and you go, that means you found something interesting and you should roll with it. All right, so that's melody.
You're now all experts. Congratulations. Let's move on to harmony. Um, so harmony is when we have two or more notes sounding at the same time. So melody has all been about one note at a time, but harmony is when you've got more than one happening. And a single instance, like a frozen moment of time,
when you've got two or more notes sounding, that's called a chord. And Sonic Pi will do chords for us much in the same way that does scales with the chord function. Again, just give it a starting note, and then autocomplete does the rest. Okay, now this list is even weirder than the last one.
The last one each at least had pronounceable words. This is, we don't know what this is. Um, well, what this is is actually kind of a shorthand notation that's used in a lot of lead sheets, um, particularly for guitar players to see, it describes what the chord is without having to spell out each note. But once again, you don't really need to know. You can just listen and see what you like.
That's kind of cool. Here's just a regular major chord. Oop, that was minor. This one's major. There we go. Seventh chord. And then you can get into the really exotic ones that have math in them basically.
That's quite nice. So now we've got a little bit of melody, and we've got a little bit of harmony, but how do we put them together? Specifically, how do you know which chords are gonna go with which melodies? Well, as it happens, that's a little outside the scope of this talk. That's a very big, broad subject.
But there's a little hack I can give you which will work around that, which is that any chord can be turned into a melody simply by articulating the notes of the chord one at a time. In music, we call this an arpeggio, and actually there's quite a lot of music that works like this. Turn this down.
So there's a major chord, but you might know this tune. It's just an arpeggio. Too soon? But anyway, it's just a chord. This one you might know.
Two chords. This one and this one. How lazy is that? If Mozart can do it, you certainly can. So let's see how that might work. Let's set up a loop again,
and we're gonna take a chord, and we're gonna assign it to a variable. So we'll just call this coolchord, and we'll use that one. And then we will play the chord, and we'll let it ring out for a few beats. And while that chord is ringing out,
we'll construct a little melody based on the notes of the chord. So let's give it 16 times, and then we'll play coolchord. I'm really glad Andy and Evan aren't up here, Adam and Evan aren't up here to provide running commentary while I code.
We'll choose, and we're gonna make these notes a little bit short because they're gonna go by kind of fast. So again, this is gonna play the chord, and then while that chord is playing, we're just gonna do 16 little notes
based on the individual notes of the chord and see what that sounds like. So it works. Let's try a different chord.
This one's kind of fun. Let's speed these up even a little more. Very nice. Now we can also change this note around a little bit
and just give it some movement. So that's working pretty well. So it might be nice to automate this movement of the chord so the starting note kind of shifts around a little bit. So we're programmers. We can do that. So let's create a list of notes, and we'll just kind of play around,
jump up a couple, jump back down, and that'll work. And then in here, instead of a hard-coded value, we'll use the start notes list, and there's a super handy function in Sonic Pi called tick, and tick is just a counter that increments automatically starting at zero.
The first time you call it, you get zero. The next time you call it, you get one. The next time you call it, you get two. And so it's super handy for iteration like this. So this is gonna take me through my chords one at a time. Now, of course, there's a problem lurking here, which is that my list only has four elements, and tick just keeps going on forever.
So pretty soon, tick's gonna get to four. It's gonna ask for index four in starting notes and kablooey, nills. No good. There's a couple ways around this. One is that we could check the value of tick, and when it gets to four, we reset the tick and start over. There's a method to do that. But there's actually an easier way, which is to use a data structure
that Sonic Pi has called a ring, and we can change it into that data structure by calling ring on the list. And a ring is a special kind of list that you can iterate over forever because the elements in the list just keep repeating themselves. So instead of a long list, it's a ring in a circle. So in this case,
if I've got a ring, and I access index four, instead of getting nil, it's gonna jump back to the first element. And five will go to here, six will go to here, seven will go to here, and then on and on. So tick can just keep going forever, and it won't get a nil.
And that'll just keep going forever until I guess we hit the logical number of how high ints can go.
So now we've got melody and harmony working together. That's great. Let's move on to rhythm. So rhythm deals with relative durations of notes. It has to do with the time aspect of music. Now we've already kind of been working with rhythm with our sleep commands because that tells us how long to wait. But one of the more interesting ways
to work with rhythm is creating drum beats. So let's start doing that. And as we do that, we're gonna change gears a little bit. All the sounds we've been using in Sonic Pi so far have been synthesized sounds, which means that Sonic Pi is doing all this crazy math behind the scenes to figure out what the waveform should look like
and send that instructions down to the sound driver, move the speakers. It's pretty complicated. But there's another way to generate sound in your music, which is called sampling. And if you ever listen to any hip-hop music ever, you probably know a little bit about sampling. A sample is just a pre-recorded sound. It could be a very short sound, or it could be a long sound,
and that sound gets played back in the context of music. Triggering a sample is no different than hitting play on your iPod. It's just a sound file that exists on disk, and it's getting played back. So we do that in Sonic Pi with the sample command. And as you can see, there's a bunch of samples built in that we can use.
So let's try a snare drum sound. Sounds pretty realistic because it's just a recording, and we're playing back the recording. One fun thing to do with samples is to play around with the rate. So a rate of one means we're playing it one times as fast. If we put in two, we go twice as fast.
So that affects not only the length of the sample, but also the pitch. The more we crank that up, the higher it goes. If you do that on a voice, you get Alvin and the Chipmunks. This is no different than changing the speed on a turntable. But you can also slow it down, or even way down.
Anybody want to guess what happens if I put in a negative number? Backwards. Or even very slowly backwards. All that with just that one little sound.
So now we've got some samples. We can start making some drum beats. So let's try a real simple one. We'll use... Let's use a bass drum. This house one is nice. Then we'll sleep.
There we go. We got a nice four-on-the-floor thing that the kids can dance to. But let's say we want to mix that up a little bit. Let's throw in a snare drum that happens every other beat. That's a pretty common pattern. So how do we want to do every other beat? Well, our old friend Tick can help us out here, too.
So we'll say we want the snare drum sound if Tick is odd. First time it'll be zero. Second time it'll be one, and so on. Now we've got that going. Makes you want to moonwalk, doesn't it?
Now this could get pretty complicated pretty fast. This is a pretty simple beat, and it's already a few lines of code. If we wanted to layer in more stuff beyond that, it could get tricky. Well, sampling can help us with this, too, because there are a certain class of samples that are almost like small pre-recorded pieces of music that can be looped, played over and over again.
These are called looping samples. And Sonic Pi has a few of these built in, too. And they start with the word loop in the list. So here's a drum sample that's ready to be looped. This is perhaps the most famous sample in history. Now that's a nice, full drum beat. It's got cymbals, it's got snare drum,
it's got bass drum. We didn't have to write any of it. It's all there. But obviously we don't want it to play once. We want it to repeat. So we'll do the loop here. And now we've got to put in a sleep, but how long is the sleep for? Well, it sounds like it's about two beats.
Let's give that a try. Now that's not really working. The reason is that the sample is just a recording of a piece of music. It doesn't have any sort of information about its tempo that Sonic Pi can sync to. It's just a data file.
So what we're trying to do is tell Sonic Pi to play the sample, and then as soon as it's done, start over again. And so we want a sleep for exactly the length of the sample, whatever that happens to be. Well, fortunately, Sonic Pi can give that for us with the sample duration method. And we just pass in the name of the sample,
and now we're saying, okay, play the sample, and then however long that sample is, I don't care, wait that long, and then play it over again. And it's as though we coded it ourselves.
So now that we've got some drum beats, this is great. Why don't we add that to this little bloop-y thing we were doing over here, so we can have melody, harmony, and a nice rhythmic thing happening at the same time. And it doesn't work. Why doesn't it work? Because we've got a nasty infinite loop up there,
and we never break out of that, and so we never get down to the loop on the bottom. So we've got one chunk of code that we need to execute, and we've got another chunk of code that we need to execute at exactly the same time. Oh, dear, looks like we're gonna have to use threads. Now, threading is often a very, very difficult and painful part of programming,
but happily, Sonic Pi has a threading model of its own built in that's kind of a dream to use. We just call in thread, give it a block, and we're done. That code will execute in its own thread, and that block at the bottom
will start at exactly the same time. We don't have to worry about the timing. Sonic Pi will do it for us. Okay, better, but they're playing at the same time. That's great, and we had to add one line of code. Awesome, we're happy, but the two pieces of music aren't in sync,
and this goes back to the same problem about this sample not having any internal sense of tempo that we can grab onto and sync up to. Fortunately, Sonic Pi can help us there with an option called beat stretch.
So what I'm doing here is saying, okay, Sonic Pi, play this sample, but I want you to adjust the rate for me. Either speed it up, slow it down, do whatever you have to do, but make sure the length of the time it takes to play the entire sample fits two beats exactly. Just lock it in for us. And once we've done that,
we can now change our sleep to two. Oops, sleep, sleep. Talking to my daughter, sleep, sleep. And now, now it's all synced up for us. So we've got melody, we've got harmony,
we've got some rhythm. Let's talk about timbre. So like I said, timbre talks about kind of the sound of the instruments that you're working with. So let's go back to an earlier example of just playing a melody. So by default, Sonic Pi chooses a synthesizer for us,
and that's this little bloopy sound that we've been hearing. But there are lots of other synthesizers built in that we can use, and we can select them with the use synth method. So here's our autocomplete list. Beep is the one that it does by default, but we could try this one. Or even this one.
Yep, that's one. So exact same notes, exact same rhythm, but each one has a totally different feel to it, depending on what the instrument is. So you can sit there and just play around with that.
Now once you have picked a synthesizer, there's more shaping you can do on top of that by throwing in more options to the play function. We talked about attack and release to control the way it sounds. There's another fun one called cutoff, and cutoff applies a filter to the sound.
Now when we hear these notes playing, there's really only one note that we hear more than any other. That's what gives it kind of its musical quality. But every sound that we hear has lots and lots of frequencies that are happening at the same time. Most of them we can't pull out and isolate. They're just part of the overall jumble. But the relative volume of all those frequencies that are happening are what gives sound its character.
And with cutoff, you have a chance to just chop off frequencies at a certain level. So if I set a relatively low cutoff, which is like 50, well, let's hear this without the filter. So if I set a lower cutoff,
then basically all of the higher frequencies are thrown out. And it starts to sound a little more dull. With a higher cutoff, those frequencies open up. And one fun thing to do with cutoff is randomize it. So let's try this.
So that creates a little bit of movement, and it almost sounds like the notes are being accented, but they're just popping out a little bit more because they're brighter. But one of the really fun things to do
in the world of timbre is to play with the built-in sound effects. So if you've ever seen a band playing, you've probably seen the guitar up on the front of the stage, and they've got a whole bunch of pedals in front of them. And they're playing along, and they stomp on the pedals, and suddenly the sound of their guitar changes drastically. So these are called effects. And it's a way of providing some sort of
interesting sonic sheen onto the music as it's coming out as a whole. So let's take kind of a simple example here. Just a couple beeps and bloops. And let's say we want to throw some reverb on that. So we use effects with the with fx command. And once again, autocomplete to the rescue.
And once again, we use a block. So we're saying this chunk of code should be passed through the reverb. That was a little subtle. I can change the parameters. I can make the room bigger so it's as though it's playing in a bigger room.
You can play with the mix. With zero, you're hearing no reverb. With one, you're hearing all reverb. That was some great faces right there. All around the room. And there's many more parameters to play with.
You can also apply some echo. Echo. And you can play around with a bunch of parameters there. Now what if you want to do reverb and echo at the same time? You just nest the calls and nest the blocks.
And you can nest those as far as your CPU can handle. Now the really nice thing about the way this is set up is that only the code within those blocks gets affected by the effect.
So if I do, let's do sleep here. And sample. And we'll go back to our snare drum again. Wherever you are. So that snare drum had no reverb or echo applied to it. But at the same time, it didn't interfere
with the reverb and the echo that was tailing off from the code above it. They just don't have anything to do with each other. And so as this block feature makes it really easy to see exactly what's going on. It's one of the most elegantly designed parts of the system, I think. All right, so let's play around with our newfound knowledge
of timbre and mix this up a little bit. So let's use a different synth for our chord. Maybe FM, that's good. And maybe we'll use TB-303 for our melody. This one I know is a little loud,
so I'm gonna turn it down a bit. And it's a totally different piece of music. Let's play with the cutoff a little bit here. We'll randomize it.
Changes it all again. Now there's one more thing I'd like to show you, which is there's a better way to do threads. As you may have noticed, every time I want to change something, I have to stop it and start over again. And if I just keep hitting run over and over again, it's gonna create new threads on top of the threads that are already playing.
That gets a little crazy in a hurry. But it's a shame to have to keep stopping. Well, fortunately, there's another way to do threads, and it's called the live loop. And a live loop is sort of a thread and a loop
combined into the same thing. You have to give it a name, so we're gonna call that one beeps. We'll get rid of this end. We'll do a live loop here. Call this one drums. Now I can keep hitting run,
and I don't get that buildup each time. Because it's got the names, it knows not to reload a new one. But the other thing that's really cool about this is I can make changes, and then when I hit run again, it will pick up those changes, and the next time through the loop, they're integrated. So let's change this around some more.
Let's change this one. New synthesizer there. And maybe we'll add a little more attack to this one so it swells up.
And we've been sticking with this chord for a while. Let's try a different one.
Then I will slow down everything. And this is what makes the live coding and performance aspect possible.
Thank you very much. This is how Sam and others do their DJ sets. They just can let these live loops run and swap them out on the fly, create new loops, and it's really cool. And the nice thing about it is it doesn't take you out of your flow.
And you can do this, too. You can just start really simple, then add things. But the thing is, when the music keeps going, you just kind of get sucked in. So some next steps for you. If you haven't already done it, download and install Sonic Pi.
It's completely free. It works great. There's an excellent help system built in. It has a great tutorial that goes in detail through all the different things it can do. There's great documentation for all the different method calls that are available. There's also a whole bunch of examples there that range from the very simple to the very complex.
And you can just copy and paste them into the editor and start hacking on them. And finally, just play with it. I've given you a lot of information and a lot of stuff, and we're all full of information from three days at the conference. But this is a system that really just invites you to just fool around with it and see what happens.
So try keeping it open in your desktop at work. When you've got a little pause, you've got to run a long test suite, or the internet goes down, just pop over, type a few lines, make some sounds, then you have some background music for when you do start typing again. So thank you for your attention. That's where you can get Sonic Pi.
That bit.ly goes to a gist that has almost all the examples that I used here today, so feel free to mess around with those. I'm Darren Wilson on Twitter. If you start playing around with this, I'd love to hear what you do, so let me know. And if you have questions, if you get stuck on something, if you want to pair sometime, I would love to.
I think this is a fantastic system, and I encourage you all to try it. Thank you. I've got a few minutes, so I could take some questions if you have any. Yeah.
The question was, can you create your own synths? Yes, you can hack the source code and submit a PR. But it's built on a, synths are all built on a system called Super Collider, and there's a lot of documentation around how to do that, and so you could plow through the source code and see.
I think it might not be as hard as you think. I say that as a person that hasn't done it. Any other questions? Yeah. Is there a way to take a picture of sheet music and use notes for that? Theoretically, yes. I've seen systems that do OCR.
That will turn a piece of sheet music into MIDI, which is a format for specifying notes and pauses and rhythms. As far as I know, there is not any kind of MIDI to Sonic Pi converter. Someone might be working on it. I'd say it's a distant theoretical possibility, not doable right now.
Yeah, sure, because one of the things I didn't show you is that with the sample feature, you can actually use samples off your local desktop, and not just the ones
that are built into Sonic Pi. So if you've got a file on disk that's got some guitar sounds in it, you could totally integrate that, and you could use less electronically sounds if that's what you wanted to do. The disadvantage of that is that the system is not quite as portable that way. One of the nice things about the way the system works is all the instructions are text,
so that's why I was able to post a gist with all the music that I did today. You can copy and paste something and send an email to somebody, and they'll have it for real, but if you're using your local samples, then you have to send that person the samples, and it becomes a little trickier, but it's possible.
Oh, does it have support for other formats like VST and other soft synths? Not right now, as far as I know. I don't know if anybody's working on it. Yeah. You can't export as MIDI.
The question was, can you export as MIDI or MP3? You can't export as MIDI, but there is a record function on there that will record your performance and save it off as a WAV file, and then from there, you can turn it into an MP3.
So the question is, does Sonic Pi have any sequencing capabilities where you can set up patterns and say, play this section, play this section, play this section? There isn't anything built in the API to do that, but you could certainly do it with Ruby,
because you can define your own functions. That was something I didn't show, and certainly you can do things with loops and say, you know, play this part five times, and then it'll drop down to the next part. So you can certainly code it. And I have a, if you go to my GitHub gist, I actually did a matrix-style drum machine,
so just a little API for, if you've ever worked with those, like the old Roland drum machines, I built something to kind of simulate that. I am an enthusiast, but hope to one day be a contributor when I grow up.
I got time for one more. Yeah, sorry? Oh, gems. No, not at this point. I mean, you could integrate into the source code, but not within the code that you're writing.
Okay, I'm out of time, but I'll be wandering around and getting lunch, so if you have any other questions, feel free to grab me. Thank you so much.