## Wednesday, October 13, 2010

### Installing

BBCut2 is a nifty library for doing break beat cutting. To use it, you must first install it. It is not available as a quark, alas. To get the library, download it from http://www.cogs.susx.ac.uk/users/nc81/bbcut2.html. Then unzip it. Inside, you will find several directories.

1. Move the "bbcut2 classes" directory to ~/Library/Application\ Support/SuperCollider/Extensions . That tilda represents your home directory, so if your user name is nicole, you would put the file in /Users/nicole/Library/Application\ Support/SuperCollider/Extensions . If the Extensions directory does not exist on your system, then create it.
2. Put the "bbcut2 help" directory inside the classes directory that you just moved.
3. Put the "bbcut2 ugens" directory in ~/Library/Application\ Support/SuperCollider/Extensions/sc3-plugins . If this directory does not exist, then create it.
4. Take the contents of the "bbcut2 sounds" directory and put them in the sounds folder with your SuperCollider application. so if you have SuperCollider in /Applications, you would put the contents of "bbcut2 sounds" in /Applications/SuperCollider/sounds

Then, re-start SuperCollider. Depending on what version of SC you have, you may have duplicate classes. If you do, there will be errors in the post window. If you see that this is a problem for you, go find the files in the BBCut classes and delete them, making sure to keep the other copy. The error message will tell you where to find the files and which ones they are.

### The Clock

BBCut relies on a clock. When I'm coding, I usually base the clock off the default clock:

 TempoClock.default.tempo_(180/60);
clock = ExternalClock(TempoClock.default);
clock.play;


The tempo is defined as beats per second. That's beats per minute, divided by 60 seconds. In the above example, the clock rate is 180 bpm, which is then divided by 60 to set the tempo. If you wanted a clock that was 60 bpm, you would set tempo_(60/60), or for 103 bpm, it would be tempo_(103/60)

BBCut uses an ExternalClock, which uses a TempoClock, so in the above example, I give it the default TempoClock. I don't have to use the default one, but could declare a new one if I wanted: clock = ExternalClock(TempoClock(182/60));

The next step is to the clock to play. If you forget this step (which I often do), nothing happens later on. Telling the clock to play is important. BBCut relies on this clock.

### Working with Buffers

There is a special sort of buffer used by BBCut, called a BBCutBuffer. The constructor for this takes two arguments. The first is a string which should contain the path and file name of the file. The second argument is the number of beats in the file. For example, we could open one of the sound files that came with BBCut:

 sf= BBCutBuffer("sounds/break",8);


We need to wait for the Buffer to load before we can start using it. One way to do that is to put the code that relies on the Buffer into a Routine. And then, we can tell the Routine to wait until the server is ready to carry on.

 sf= BBCutBuffer("sounds/break",8);

Routine.run({
s.sync; // this tells the task to wait
// below here, we know all out Buffers are loaded
. . .
})


Now we can tell BBCut that we want to cut up a buffer and get it to start doing that.

  cut = BBCut2(CutBuf3(sf)).play(clock);


BBCut2 is the class that runs everything, so we make a new one of these. Inside, we pass a CutBuf, which is a class that handles Buffer cutting. We tell the BBCut2 object to play, using the clock. This starts something going.

Cutting is much more interesting if it can jump around in the buffer a bit:

  cut = BBCut2(CutBuf3(sf, 0.4)).play(clock);


We can specify the chances of a random cut. 0.0 means a 0% chance and 1.0 is a 100% chance. We can set the chances at any numbers between and including 0.0 to 1.0. If we want a 40% chance of a random jump, we would use 0.4.

### Cut Procedures

We can tell BBCut to use one of several cut procedures. The original one is called BBCutProc11.

  cut = BBCut2(CutBuf3(sf, 0.4), BBCutProc11.new).play(clock);


It can take several arguments, which are: sdiv, barlength, phrasebars, numrepeats, stutterchance, stutterspeed, stutterarea

• sdiv - is subdivision. 8 subdivsions gives quaver (eighthnote) resolution.
• barlength - is normally set to 4 for 4/4 bars. If you give it 3, you get 3/4
• phrasebars - the length of the current phrase is barlength * phrasebars
• numrepeats - Total number of repeats for normal cuts. So 2 corresponds to a particular size cut at one offset plus one exact repetition.
• stutterchance - the tail of a phrase has this chance of becoming a repeating one unit cell stutter (0.0 to 1.0)

For more on this, see the helpfile. In general, the cut procedures are very well documented. Here's an example of passing some arguments to BBCutProc11:

  cut = BBCut2(CutBuf3(sf, 0.4), BBCutProc11(8, 4, 2, 2, 0.2).play(clock)


We can tell the cutter to stop playing, or free it

  cut.stop;
cut.free;


Putting all of what we have so far together, we get:

(
var clock, sf, cut;

TempoClock.default.tempo_(180/60);
clock = ExternalClock(TempoClock.default);
clock.play;

sf= BBCutBuffer("sounds/break",8);

Routine.run({
s.sync; // this tells the task to wait

cut = BBCut2(CutBuf3(sf, 0.4), BBCutProc11(8, 4, 2, 2, 0.2)).play(clock);

30.wait; //  // let things run for 30 seconds

cut.stop;
cut.free;
})
)


There are several other cut procedures, like WarpCutProc1 or SQPusher1 or SQPusher2. If you go look at the main helpfile, you can find which ones are available. This file is called BBCut2Wiki (and is found at ~/Library/Application\ Support/SuperCollider/Extensions/bbcut2\ classes/bbcut2\ help/BBCut2Wiki.help.rtf or by selecting the text BBCut2Wiki and typing apple-d )

### Polyphony

The clock keeps things in sync, so you can run two different cut procedures at the same time and have things line up in time.

  cut1 = BBCut2(CutBuf3(sf, 0.4), BBCutProc11(8, 4, 2, 2, 0.2)).play(clock);
cut2 = BBCut2(CutBuf3(sf, 0.2), WarpCutProc1.new).play(clock);


You can even mix and match sound files:

(
var clock, sf1, sf2, cut1, cut2, group;

TempoClock.default.tempo_(180/60);
clock = ExternalClock(TempoClock.default);
clock.play;

sf1= BBCutBuffer("sounds/break",8);
sf2= BBCutBuffer("sounds/break2",4);

Routine.run({
s.sync; // this tells the task to wait

cut1 = BBCut2(CutBuf3(sf1, 0.4), BBCutProc11(8, 4, 2, 2, 0.2)).play(clock);
cut2 = BBCut2(CutBuf3(sf2, 0.2), WarpCutProc1.new).play(clock);

15.wait;
cut1.stop;
cut2.stop;
})
)


If you want to also sync up a Pbind, you can use BBcut's clock via the playExt method:

Pbind.new(/*  . . . */ ).playExt(clock);


Or, if you want to play an Event, you can use the tempo clock associated with the external clock

Event.new.play(clock.tempoclock);


### Groups and FX

If we want to add fx to the chain, and take them back out, we can use a thing called a CutGroup:

  // make a group with a Buffer
group = CutGroup(CutBuf3(sf1, 0.4));
// then send it to get cut up
cut1 = BBCut2(group, BBCutProc11(8, 4, 2, 2, 0.2)).play(clock);
// then put some FX in the chain


The CutGroup acts like an array, which holds our CutBuf and also the fx. To get an idea of how this works, try running the following code, adapted from CutGroup's help file:

(
var sf, clock;

clock= ExternalClock(TempoClock(2.5));

clock.play;

Routine.run({

sf= BBCutBuffer("sounds/break",8);

s.sync; //this forces a wait for the Buffer to load

g=CutGroup(CutBuf1(sf));

BBCut2(g, WarpCutProc1.new).play(clock);
});

)

//run these one at a time

g.cutsynths.postln;

g.cutsynths.postln;

g.removeAt(2);  //remove comb

g.cutsynths.postln;


And also notice that you may get some errors in the post window when you remove fx: FAILURE /n_set Node not found. These are not usually a problem.

### Tying it all Together

Here's an example using everything covered so far:

(
var clock, sf1, sf2, cut1, cut2, group;

TempoClock.default.tempo_(180/60);
clock = ExternalClock(TempoClock.default);
clock.play;

sf1= BBCutBuffer("sounds/break",8);
sf2= BBCutBuffer("sounds/break2",4);

Routine.run({
s.sync; // this tells the task to wait

group = CutGroup(CutBuf3(sf1, 0.2));  // make a group with a Buffer
cut1 = BBCut2(group, BBCutProc11(8, 4, 2, 2, 0.2)).play(clock);  // then cut it up

5.wait;

cut2 = BBCut2(CutBuf3(sf2, 0.2),
BBCutProc11(8, 4, 4, 2, 0.2)).play(clock); // start more drums from the other sound file

5.wait;

group.add(CutComb1.new); // put some FX on the drums in cut1

15.wait;

group.removeAt(2); // take the fx back off

1.wait;
cut2.pause;

4.wait;
cut1.stop;
})
)


#### Summary

• You must download BBCut2 from a website and install it by moving folders around.
• The main BBCut helpfile is BBCut2Wiki
• BBCut uses it's own clock, called ExternalClock, which relies on TempoClocks.
• You must remember to start the clock
• BBCut uses it's own buffer class called BBCutBuffer. The constructor takes two arguments: a string with the path and filename, and the number of beats in the sound file. If you get the number of beats wrong, your results may sound weird.
• There are several cut procedures, one of which is called BBCutProc11. To use it, (or any other cut procedure in it's place), you use the construction BBcut2(CutBuf1(sf), BBCutProc11.new).play(clock)
• The cut procedures all have good help files.
• Due to the magic of clocks, you can start two BBCuts going at the same time and if they have the same clock, they will line up.
• It is possible to add FX or remove FX from your chain by using CutGroup.

#### Problems

1. Get some of your own drum loops or rhythmic samples and try this out. You can find many loops at http://www.freesound.org/. Also, try some files with sustained tones.
2. Experiment with the arguments to BBCutProc11. Try your files with several different values.
3. Try out the different cut procedures. Look at their help files to find their arguments.
4. The FX are not as well documented, but they're located in ~/Library/Application\ Support/SuperCollider/Extensions/bbcut2\ classes/cutsynths/fx . Try several of them out.

### Waiting

Last time, we learned that the language does not wait for the server to finish loading buffers before it carries on with the programme, which could lead to a situation where we instruct the server to start playing a buffer that hasn't yet loaded. This will fail to play correctly. Fortunately, there are a few ways to make sure this doesn't happen.

If we use a Task (or a Routine), we can tell it to pause until the server has caught up.

s.boot;

(
var buf;

SynthDef(\playBufMono, {| out = 0, bufnum = 0, rate = 1 |
var scaledRate, player;
scaledRate = rate * BufRateScale.kr(bufnum);
player = PlayBuf.ar(1, bufnum, scaledRate, doneAction:2);
Out.ar(out, player)

s.sync; // wait for the server
Synth(\playBufMono, [\out, 0, \bufnum, buf.bufnum, \rate, 1])

}).play
)


The s.sync makes the Task wait for the server to get caught up with the language. The SynthDef, like the buffer, is also asynchronous, so the sync gives everything a chance to get caught up.

We can also give the buffer an action. This is a function that gets evaluated when the buffer has finished loading. This might be a good idea when we are going to load several buffers, but don't need to use all of them right away. We could use the action, for example, to set a flag so our programme knows it's ok to start using the buffer:

s.boot;

(

SynthDef(\playBuf, {| out = 0, bufnum = 0, rate = 1,
dur = 0.2, amp = 0.2, startPos = 0 |
var scaledRate, player, env;

env = EnvGen.kr(Env.sine(dur, amp), doneAction: 2);
scaledRate = rate * BufRateScale.kr(bufnum);
player = PlayBuf.ar(1, bufnum, scaledRate,
startPos: startPos, loop:1);
Out.ar(out, player * env)

Pseq([
Pbind( // play this Pbind first
\scale,  Scale.gong,
\dur,   Pwhite(1, 3, inf) * 0.001,
\degree,  Prand([0, 2, 4, \rest], inf),
\amp,  0.2,
\test,  Pfunc({ bufloaded }) // when this is nil, this Pbind ends
),
Pbind( // next play this one
\instrument, \playBuf,
\bufnum,  Pfunc({buf.bufnum}), // use the buffer, now that we know it's ready
\dur,  Pwhite(0.01, 0.3, 20),
\startFrame, Pfunc({buf.numFrames.rand}),
\amp,  1
)
], 1). play

)



Recall that when a Pbind gets a nil, it stops playing and the pattern goes on to the next section, so setting the flag to nil, in this case, advances the piece. Because the second buffer has not yet loaded when the interpreter first evaluates the second Pbind, buf.numFrames will still be nil. Therefore, we put that into a Pfunc so that it gets evaluated when the Pbind plays, instead of when the interpretter first looks at the code.

In that example, we don't always start playing back at the start of the Buffer, but instead offset a random number of samples (called "Frames" here). Coupled with the short duration, this can be an interesting effect.

When you are writing your own actions, you can also do a more typical true / false flag or do anything else, as it's a function. For example, it's possible to combine the two approaches:

s.boot;

(
var buf1, syn, pink;

SynthDef(\playBuf1, {| out = 0, bufnum = 0, rate = 1, loop = 1 |
var scaledRate, player;
scaledRate = rate * BufRateScale.kr(bufnum);
player = PlayBuf.ar(1, bufnum, scaledRate, loop: loop,
doneAction:2);
Out.ar(out, player)

SynthDef(\playBufST, {| out = 0, bufnum = 0, rate = 1, loop = 1,
dur = 1, amp = 0.2 |
var scaledRate, player, env;

env = EnvGen.kr(Env.sine(dur, amp), doneAction: 2);
scaledRate = rate * BufRateScale.kr(bufnum);
player = PlayBuf.ar(2, bufnum, scaledRate, loop:loop);
Out.ar(out, player * env)

s.sync; // wait for buf1
syn = Synth(\playBuf1, [\out, 0, \bufnum, buf1.bufnum,
\rate, 1, \loop, 1]);  // play buf1

action: {  // run this when pink loads
syn.set("loop", 0);
syn = Synth(\playBufST, [\out, 0, \bufnum, pink.bufnum,
\rate, 1, \loop, 1, \dur, 10]); // play pink
});

}).play
)


In the above example, we first wait for the allwlk01 buffer to load and then start playing it. While it's playing, we tell the SinedPink buffer to load also and give it in action. When it has loaded, the action will be evaluated. The action tells the first synth to stop looping and then starts playing a new Synth with the new buffer.

If we wanted to, we could use the action to set a flag or do any number of other things.

### Recording

We don't need to just play Buffers, we can also record to them. Let's start by allocating a new Buffer:

b = Buffer.alloc(s, s.sampleRate * 3, 1)


The first argument is the server. The second is the number of frames. I've allocated a 3 second long Buffer. The third argument is the number of channels.

Now, let's make a synth to record into it:

 SynthDef(\recBuf, {| in = 1, bufnum, loop = 1|

var input;
input = AudioIn.ar(in);
RecordBuf.ar(input, bufnum, recLevel: 0.7, preLevel: 0.4, loop:loop, doneAction: 2);


AudioIn.ar reads from our microphone or line in. Channels start at 1, for this UGen.

RecordBuf takes an input array, a bufnum and several other arguments. In this example, we're scaling the input by 0.7 and keeping previous data in the buffer, scaled by 0.4. We'll keep looping until instructed to stop.

We can mix this with a stuttering playback from earlier:

s.boot;

(
var buf, syn, pb;

SynthDef(\playBuf2, {| out = 0, bufnum = 0, rate = 1,
dur = 5, amp = 1, startPos = 0 |
var scaledRate, player, env;

env = EnvGen.kr(Env.sine(dur, amp), doneAction: 2);
scaledRate = rate * BufRateScale.kr(bufnum);
player = PlayBuf.ar(1, bufnum, scaledRate,
startPos: startPos, loop:1);
Out.ar(out, player * env)

SynthDef(\recBuf, {| in = 1, bufnum, loop = 1|

var input;
input = AudioIn.ar(in);
RecordBuf.ar(input, bufnum, recLevel: 0.7, preLevel: 0.4, loop:loop, doneAction: 2);

buf = Buffer.alloc(s, s.sampleRate * 3, 1);

s.sync; // wait for the buffer

syn = Synth(\recBuf, [\in, 1, \bufnum, buf.bufnum, \loop, 1]); // start recording

2.wait; // let some stuff get recorded;

pb = Pbind( // play from the same buffer
\instrument, \playBuf2,
\bufnum,  buf.bufnum,
\dur,  Pwhite(0.01, 0.5, 2000),
\startFrame, Pwhite(0, buf.numFrames.rand, inf),
\amp,  1
).play;

5.wait;

syn.set("loop", 0);  // stop looping the recorder

3.wait;
pb.stop; // stop playing back
}).play
)


#### Summary

• Buffers load asynchronously and we can't count on them to be ready unless we wait for them.
• One way to wait is to call s.ync inside a Task or a Routine.
• We can start playing back a Buffer from any sample with the startFrame argument.
• Buffer.read has an action argument, to which we can pass a function that will be evaluated after the Buffer has been read on the server.
• We can allocate empty Buffers on the server with Buffer.alloc.
• AudioIn.ar starts with channel 1, even though most other input busses start at 0.
• RecordBuf.ar records to a Buffer.

#### Problems

1. Write a programme that opens and plays several Buffers. Make sure that every Buffer is ready before you play it. Spend the least possible amount of time waiting.
2. Write a programme that reads a Buffer, starts playing it back in some way and the starts recording to the same Buffer. You can use AudioIn.ar or check out InFeedback.ar. Note that, as the name implies, you may get feedback, especially if you are playing back in a linear manner at a rate of 1. Try other rates or ways of playing back to avoid this.
3. Find a short audio file that contains some beat-driven audio. If you know the number of beats in the file, could you make an array of startFrames? Write a Pbind that does something interesting with your file and your array.

## Sunday, October 03, 2010

### Working with Buffers

Let's say you want to open a short audio file and play it back. You can do this with a Buffer.

 s.boot;


Don't run both of those lines at once. Wait for the server to finish booting before reading the Buffer. The reason you need to wit is because the Buffer actually lives with the server. The server plays the audio, so the server needs to have the audio in it's memory.

The first argument, is therefore the server that will hold the buffer. The second is the path to the buffer on your computer.

Because the Buffer lives with the server, the command to read it is asynchronous. We tell the server to load the Buffer and then carry on, without waiting to hear back if it's been loaded or not. For large files, it may take a few moments for it to fully load. One way to deal with tis is to load buffers into global variables (like b, above) and then manually wait to evaluate the next section.

### PlayBuf

To play the Buffer, you can use the UGen PlayBuf:

(
SynthDef(\playBuf, {| out = 0, bufnum = 0 |
var scaledRate, player;
scaledRate = BufRateScale.kr(bufnum);
player = PlayBuf.ar(1, bufnum, scaledRate, doneAction:2);
Out.ar(out, player)
}).play(s, [\out, 0, \bufnum, b.bufnum]);
)


When Buffers are allocated on the server, they're given a unique ID number, so we can reference them later. This number is called the bufnum. It's the second argument to the SynthDef. This way, we know which buffer we're supposed to play.

Some Buffers may have unusual sample rates or otherwise be unusual. To make sure that they play at the speed we expect, we use a UGen to scale the rate. If we wanted to play at half speed, we could change the SynthDef:

(
SynthDef(\playBuf, {| out = 0, bufnum = 0, rate = 1 |
var scaledRate, player;
scaledRate = rate * BufRateScale.kr(bufnum);
player = PlayBuf.ar(1, bufnum, scaledRate, doneAction:2);
Out.ar(out, player)
}).play(s, [\out, 0, \bufnum, b.bufnum, \rate, 0.5]);
)


Note that when we play at half speed, it takes twice as long to play the sample and pitches are all an octave lower. This is just like working with magnetic tape. If we change the rate to 2, it will play back at half the speed of the original and be an octave higher. If you try a rate of -1, it will play backwards at the normal rate.

The PlayBuf UGen is the one that actually plays the buffer. The first argument is the number of channels. Our buffer is mono, so that number is 1. If it were stereo, we would change it to 2. You cannot pass in this number as an argument or change it while the Synth is running. The SynthDef must be defined with the right number of channels. If you give a stereo buffer to a mono PlayBuf, or vice versa, it will not play. If you have both mono and stereo buffers in one piece, you will need to have two SynthDefs:

(
SynthDef(\playBufMono, {| out = 0, bufnum = 0, rate = 1 |
var scaledRate, player;
scaledRate = rate * BufRateScale.kr(bufnum);
player = PlayBuf.ar(1, bufnum, scaledRate, doneAction:2);
Out.ar(out, player)

SynthDef(\playBufStereo, {| out = 0, bufnum = 0, rate = 1 |
var scaledRate, player;
scaledRate = rate * BufRateScale.kr(bufnum);
player = PlayBuf.ar(1, bufnum, scaledRate, doneAction:2);
Out.ar(out, player)
)


PlayBuf can handle N-channel files, so if you have some three channel or 8 channel files, you can also play those if you define synthdefs with the right number of channels.

To figure out which SynthDef to use, you can send the message numChannels to a buffer object:

(
if((b.numChannels == 1), {
Synth(\playBufMono, [\out, 0, \bufnum, b.bufnum, \rate, 1])
}, {
if((b.numChannels == 2), {
Synth(\playBufStereo, [\out, 0, \bufnum, b.bufnum, \rate, 1])
})
});
)


The second argument to PlayBuf is the bufnum. This tells it which Buffer to play.

The third argument is the rate. As mentioned above, it's a good idea to scale this rate with BufRateScale.kr

Buffers, like envelopes, can have a doneAction. 2 means to deallocate the synth from the server when the Buffer stops playing.

If you want to loop your buffer, that's also a possible argument:

(
SynthDef(\playBufMonoLoop, {| out = 0, bufnum = 0, rate = 1 |
var scaledRate, player;
scaledRate = rate * BufRateScale.kr(bufnum);
player = PlayBuf.ar(1, bufnum, scaledRate, loop: 1, doneAction:2);
Out.ar(out, player)
}).play(s, [\out, 0, \bufnum, b.bufnum, \rate, 1]);
)


1 means do loop and 0 means don't loop. the default is 0. You can change the loop value while the Synth is running, so it's a good idea to still have a doneAction.

You can trigger a PlayBuf to jump back to the start:

(
SynthDef(\playBufMonoStutter, {| out = 0, bufnum = 0, rate = 1 |
var trigs, scaledRate, player;
trigs = Dust.ar(2);
scaledRate = rate * BufRateScale.kr(bufnum);
player = PlayBuf.ar(1, bufnum, scaledRate, trigs, loop: 1, doneAction:2);
Out.ar(out, player)
}).play(s, [\out, 0, \bufnum, b.bufnum, \rate, 1]);
)


Dust.ar returns impulses at random intervals. It's argument is the average number of impulses per second.

You can also tell the PlayBuf to start someplace else than the first sample:

(
SynthDef(\playBufMonoLoopStart, {| out = 0, bufnum = 0, rate = 1, startPos |
var scaledRate, player;
scaledRate = rate * BufRateScale.kr(bufnum);
player = PlayBuf.ar(1, bufnum, scaledRate, startPos: startPos, loop: 1, doneAction:2);
Out.ar(out, player)
}).play(s, [\out, 0, \bufnum, b.bufnum, \rate, 1, \startPos, b.numFrames.rand]);
)


startPos is the number of the sample to start from. If you have a one second long buffer with 44100 samples in it, and you want to start in the middle, you would set use 22050 for the startPos.

### Dialogs

If you don't want to have to pick an audio file ahead of time, you can use Buffer.loadDialog:


s.boot;

(
SynthDef(\playBufMono, {| out = 0, bufnum = 0, rate = 1 |
var scaledRate, player;
scaledRate = rate * BufRateScale.kr(bufnum);
player = PlayBuf.ar(1, bufnum, scaledRate, doneAction:2);
Out.ar(out, player)

SynthDef(\playBufStereo, {| out = 0, bufnum = 0, rate = 1 |
var scaledRate, player;
scaledRate = rate * BufRateScale.kr(bufnum);
player = PlayBuf.ar(1, bufnum, scaledRate, doneAction:2);
Out.ar(out, player)

)

(
if((b.numChannels == 1), {
Synth(\playBufMono, [\out, 0, \bufnum, b.bufnum, \rate, 1])
}, {
if((b.numChannels == 2), {
Synth(\playBufStereo, [\out, 0, \bufnum, b.bufnum, \rate, 1])
})
});
)


Note that you cannot load a compressed audio format like mp3 or ogg directly into a Buffer.

More on Buffers to come!

#### Summary

• Buffers live on the server
• Every Buffer has a unique bufnum
• You can change the playback rate of a Buffer. This should be scaled with BufRateScale
• SynthDefs must be sent to the server already knowing how many channels PlayBuf.ar will play.
• PlayBuf.ar will optionally take a doneAction
• You can loop a Buffer, stuter it and tell it where to start
• You can open a Buffer with a Dialog box
• You cannot read an mp3 or ogg directly into a Buffer

## Tuesday, August 03, 2010

### Event

The most important subclass of Dictionary is Event:

(
var evt;
evt = Event.new;
evt.play;
)


Much like Arrays can be declared just by square brackets, Events can be declared just with parenthesees:

( ).play;


The sonic results of that line of code might sound familiar to you:

Pbind.new.play


This is not a coincidence! Patterns create Events and play them sequentially. Compare:

Pbind(\freq, 660, \pan, -1).play


and

(freq: 660, pan: -1).play


Note that the syntax for the Event is (key: value, key2: value2) . You can have as many key: value pairs as you want. In the example above, freq and pan are both symbols, both in the Pbind and the event.

Events are Dictionaries and they are created with a bunch of default keys and values. Although, you can use any sort of object as the key for a Dictionary, you should only use symbols as keys for an Event.

The Pbind modifies elements of a default Event and then plays the results of that. To find out what interesting thigns can be changed in an Event, (and therefore also in a Pbind), check out it's helpfile, specifically the section called "Useful keys for notes."

(
Pbind(
\freq, Pseq([550], 1),
\event, Pfunc({ |evt|
evt[\freq].postln;
})
).play
)


The current event is passed as an argument to the function in Pfunc and also the one in Prout. Here, we have created a key, \event, that doesn't have meaning to the Synth, nor to the Event. This is allowed. For example:

(
Pbind(
\freq, Pseq([550], 1),
\foo, \bar
).play
)


Every time the Pbind makes an event, it goes through the list of keys and values in the order that it recieves them. For example:

(
Pbind(
\event, Pfunc({ |evt|
"Pan before: %".format(evt[\pan]).postln;
}),

\pan, Pseq([-1], 1),

\event2, Pfunc({ |evt|
"Pan after: %".format(evt[\pan]).postln;
})
).play
)

The first postln prints out 0, because that's the default value for \pan. The second postln prints out -1. Then it goes back to the first one because the Pbind does not run out the Pseq returns a nil.

Let's make the duration depend on the frequency:

(
Pbind(
\freq, Prand([440, 550, 660, 770], 10),
\dur, Pfunc({ |evt|

var dur;

dur = evt[\freq] / 1000
})
).play
)


Events are one way you can tie together two keys in an event. You can also do this with arrays:

(
Pbind(

[\freq, \dur],
Prout({
var arr, freq, dur;

arr = [440, 550, 660, 770];

10.do({

freq = arr.choose;
dur = freq / 1000;

[freq, dur].yield;
})
})
).play
)


Two or more keys can be grouped together in an array. Then, the stream, which can be a Prout, a Pfunc or any other P-thing, must return an array which is the same length as the key array. The first item in the returned array gets paired with the first item in the key array, the second item goes with the second key and so forth.

#### Summary

• Event is a subclass of Dictionary.
• You can declare an event by just using parenthesis.
• You should only use Symbols as keys for Events.
• Patterns work by creating events over and over again.
• You can access events in Pfunc. It's passed to the function as an argument.
• You can use keys in your Event or Pbind that are not meaningful to the Pbind, the Even or the Synth.
• Events can be used to tie together two different elements in a Pbind.
• Arrays can also be used to tie together two different elements in a Pbind.

## Friday, June 25, 2010

### Dictionary

Let's take a break from Pbinds and their ilk to talk about a data type. A Dictionary is a data type like an array, except that instead of using integers for indexes, you can use anything that you want.

(
var id;

id = Dictionary.new;
id.put(\foo, "bar");

id[\foo].postln;
)


The indexes are called keys and the items associated with them are called values. In the above example, \foo is the key and "bar" is the value. As mentioned above, you can use any kind of object for keys. And, like arrays, any kind of object can be the value.

(
var id;

id = Dictionary.new;
id.put(\foo, "bar");
id.put(15, true);
id.put("baz", 12.5);

id[15].postln;
)


You can get a list of the keys with the message keys, and then use that to step through a do loop:

(
var id, keys;

id = Dictionary[
\foo -> "bar",
15 -> true,
"baz" -> 12.5
];

keys = id.keys;
keys.postln;

keys.do({|key|

"key is %, value is %".format(key, id.at(key)).postln;
});
)


In that example, we see another way of declaring a Dictionary, with square brackets and key, value pairs in the format key -> value

We also see a new way of formatting strings. If you want to print a string with some variables in it, you can use % to signify where the variable should go and then pass the variables as arguments to format. You can use as many variables as you would like: "string %, % and %".format(var1, var2, var3)

Notice that the keys are in a random order. If you want them in a particular order, you will have to sort them.

Here's another example:

(
var triangle_spectrum, freqs;

triangle_spectrum = Dictionary[
1->1,
3->(1/9),
5->(1/25),
7->(1/49),
9->(1/81)
];

freqs = triangle_spectrum.keys;
freqs = freqs.asArray;
freqs = freqs.sort;

freqs.do({|freq|

"freq %\t amplitude %\n".postf(freq * 440, triangle_spectrum[freq]);
})
)


This stores the (non-normalised) spectrum of a triangle wave. Note that when we declare the Dictionary, we need to put mathematical expressions inside parentheses.

Then, we get the keys from the dictionary. Then we need to convert that Set to an Array. We can then tell the Array to sort itself.

\t means tab and \n means newline. We use these for formatting, to make our output look nice. postf formats a string and then posts it. It does not include a newline, so we do it ourselves with a \n

Array.sort takes an optional argument, which is a sort function. Here's an example to do a reverse sort:

(
var triangle_spectrum, freqs;

triangle_spectrum = Dictionary[
1->1,
3->(1/9),
5->(1/25),
7->(1/49),
9->(1/81)
];

freqs = triangle_spectrum.keys;
freqs = freqs.asArray;
freqs = freqs.sort({|a, b| a > b});

freqs.do({|freq|

"freq %\t amplitude %\n".postf(freq * 440, triangle_spectrum[freq]);
})
)


The sort function takes two agruments and returns a boolean. In the above example, it compares two items and if the first one is bigger, it returns true. This will order the array so that larger items come first.

We can check to see if a Dictionary includes a particular key:

(
var triangle_spectrum;

triangle_spectrum = Dictionary[
1->1,
3->(1/9),
5->(1/25),
7->(1/49),
9->(1/81)
];

triangle_spectrum.includesKey(4).postln;
)


We can also look for the key of a particular item:

(
var id;

id = Dictionary[
\foo -> "bar",
15 -> true,
"baz" -> 12.5
];

id.findKeyForValue(12.5).postln;
)


#### Summary

• A Dictionary is made up of key, value pairs.
• You can add items to a Dictionary with a message put(key, value)
• Dictionaries can be declared with key -> value pairs in square brackets.
• Dictionary.keys exports a set of the keys, in random order.
• If you want to sort the keys, you must pass them the message .asArray and then pass the message sort to the result of that.
• If you want to sort anyhting besides numbers from small ot large you have to write a sort function
• A sort function takes two arguments and returns a boolean based on a comparison between them.
• You can test is an Dictionary contains a particular key with includesKey
• You can look up the key for a value with findKeyForValue

## Thursday, June 24, 2010

### Streams

There's a very useful helpfile set for Streams Patterns and Events, which is available by looking for the helpfile for Streams.

We know what a pattern is, after looking at Pseq and he other Pthings. But what is a stream? "A stream represents a lazy sequence of values," says the helpfile "Understanding Streams, Patterns and Events - Part 1," which you should go read. Streams respond to the message next. Here's an example:

(
var stream;

stream = Pseq([1, 2, 3], 1).asStream;

3.do({
stream.next.postln;
})
)


Any kind of pattern can be converted to a stream by sending it the message asStream. This can be more useful than you might think. For example, if you have two threads stepping through the same data:

(

stream = Pseq(["Mary", "had", "a", "little", "lamb", "whose", "fleece"], 1).asStream;

inf.do({

stream.next.postln;
1.wait;
});
});

inf.do({

stream.next.postln;
1.51.wait;
});
});

)


The two tasks can strep through a shared list. However, note that the stream starts returning nil when it runs out of other data to return. You have to test for that:

(

stream = Pseq(["Mary", "had", "a", "little", "lamb", "whose", "fleece"], 1).asStream;

var next;

next = stream.next;

{next.notNil}.while({

("task" ++ id ++ ": " ++ next). postln;
wait.wait;
next = stream.next;
});
});
};

)


You can also do math on streams:

(
var stream, squared;

stream = Pseq([1, 2, 3], 1).asStream;
squared = stream.squared;
3.do({
squared.next.postln;
})
)


And you can do binary math operations on two streams:

(
var stream1, stream2, sum;

stream1 = Pseq([1, 2, 3], 1).asStream;
stream2 = Pseq([4, 5, 6], 1).asStream;
sum = stream1 + stream2;

3.do({
sum.next.postln;
})
)


You can use streams with Pbinds, but you have to wrap them in Prout or Pfunc:

(
var notes, pbind;

notes = Pseq([ 1/1, 3/2, 4/3, 9/8, 16/9, 5/4, 8/5 ].pyramid(1), 2).asStream;
notes = notes * 440;

pbind = { |dur = 0.5|

Pbind(
\dur, dur,
\freq, Pfunc({notes.next})
)
};

Ppar([pbind.value(0.5), pbind.value(0.751)]).play;
)


Note that when notes.next returns nil, the Pbind quits playing.

#### Summary

• Streams can be create from patterns. The respond to the message next.
• When streams run out of values, they start to return nil.
• Multiple tasks can access the same stream.
• You can do math on streams.
• Streams can be used in Pbinds, provided a function or a routine calls next

## Tuesday, June 08, 2010

### Math with Patterns & Prout

Let's say that you want to pick random numbers? You could use Pwhite. But what if you wanted random multiples of 2? You would still use Pwhite:

(
Pbind(
\dur,  0.2,
\note,  Pwhite(0, 6) * 2
).play
)


What if you want to square your random numbers?

(
Pbind(
\dur,  0.2,
\note,  Pwhite(0, 5).squared
).play
)


You can do any math operation with a pattern as if it was a number.

(
Pbind(
\dur,  0.2,
\note,  Pseq([1, 2, 3], 15) * Pseq([1, 2, 3, 5, 4], inf)
).play
)


If you want to do math with a pattern and a variable that might change over time, you still need to use a Pfunc:

(
var num;
num = 5;

Pbind(
\dur,  0.2,
\note, Pwhite(0, 5) * Pfunc({num})
).play;

5.wait;
num = 2;
}).play;
)


Let's say you want step through every item in a shuffled array. You could use Pseq:

Pseq([1, 3, 5, 7].scramble, 4)

Or Pshuf does the same thing:

Pshuf([1, 3, 5, 7], 4)

But what if you want the array to reshuffle after every tme through the loop? (As far as I know) there's not a pre-existing pattern for that. But you can write one with Prout.

(
var arr, rout;

arr = [1, 3, 5, 7];

rout = Prout({
5.do({
arr.scramble.do({|item|
item.yield;
})})
});

Pbind(
\dur, 0.2,
\note, rout
).play
)


A Routine is a function that can pause while it's running. It can also return values more than once. Prout is a wrapper for a Routine. Everytime it gets to item.yield, it returns the item and then waits to be asked for it's next return value. Then it starts running again until it finds another yield or runs out of things to run.

Like Pfunc, Prout evaluates variables as it runs. In the above example, if arr had changed, the Prout would have used the new arr:

(
var arr, rout;

arr = [1, 3, 5, 7];

rout = Prout({
10.do({
arr.scramble.do({|item|
item.yield;
})})
});

Pbind(
\dur, 0.2,
\note, rout
).play;

2.wait;
arr = [12, 15, 19, 21];
2.wait;
arr = [-12, -13, -11];
}).play
)


You could do something similar also, this way:

(
var arr1, arr2, arr3, rout;

arr1 = [1, 3, 5, 7];
arr2 = [12, 15, 19, 21];
arr3 = [-12, -13, -11];

rout = Prout({
3.do({
arr1.scramble.do({|item|
item.yield;
})});
3.do({
arr2.scramble.do({|item|
item.yield;
})});
3.do({
arr3.scramble.do({|item|
item.yield;
})})
});

Pbind(
\dur, 0.2,
\note, rout
).play;

)


You can have as many yields as you want in a Routine - or a Prout.

If you want to pass in arguments, you can use a wrapper function:

(
var rout;

rout = {|arr, repeats = 5|
Prout({
repeats.do({
arr.scramble.do({|item|
item.yield;
})})
});
};

Pbind(
\dur, 0.2,
\note, rout.value([0, 2, 4, 6], 6)
).play
)


And, as with Pfunc, you can do math:

(
var rout;

rout = {|arr, repeats = 5|
Prout({
repeats.do({
arr.scramble.do({|item|
item.yield;
})})
});
};

Pbind(
\dur, 0.2,
\note, rout.value([0, 2, 4, 5], 6) * Pseq([1, 2, 3], inf)
).play
)


Yielding only works inside Routines. If you try this in a Pfunc, it does not work:

(
var func;

func = Pfunc({
5.do({
[1, 2, 5].scramble.do({|item|
item.yield; // you can't do this in a Pfunc!!
})})
});

Pbind(
\dur, 0.2,
\note, func
).play
)


Note that it does not create an error message, it just behaves in a bizarre way. Silent errors are the hardest to track down, so beware.

#### Summary

• Patterns can behave like numbers for math operations.
• A Routine is a function that can pause
• A Prout is like a Pfunc, except that it can stop in the midst of things and resume.
• Routines can return more than one item, at any point in their execution, whenever you yield a value.
• You can only yield in a Routine or a Prout

## Sunday, June 06, 2010

### Pfunc

Let's say you want to control some part of your Pattern from, say, a task. For example, we want to execute some block of code, then wait 5 seconds and then casue the amplitude of a Pbind to fade towards zero. We can do this by using some variables:

(

db = -12;

// ...

5.wait;

60.do({

db = db - 1;
0.1.wait;
});

});

// ...
)


db will hold our amplitude in decibels. We're using db because it's logarithmic and will sound right if we just use subtraction to change the value.

task will hold our task. That "..." near the top represents whatever we wanted to do before starting the countdown to the fade-out.

After that, we wait for 5 seconds, then we slowly drop 60 db.

Now for the pbind:

 // ...

pbind = Pbind(

\dur,   Pseq([0.2, 0.4, 0.6], inf),
\degree,   Pseq([0, 3, 5, 7, 9, 8, 8, 2].pyramid(1), inf),
\steapsPerOctave, 10,
\db,    db
);

// ...



In the line for degree, we see that we're sending the message pyramid to the array. It reorders the array in an interesting way. See the helpfile for Array for more information about it.

Pbinds understand the symbol \db and will convert to amp automatically, as needed. There's a message you can pass to numbers called dbamp. It converts from db to amps. -12.dbamp is 0.25118864315096. Or if you want to go the other way, there's a message ampdb. 0.25.ampdb is -12.041199826559. However, the Pbind will do this for you, so you don't need to convert ahead of time.

Now we can try running the task and the pbind simultaneously:

 // ...

pbind.play;


And when you put this all together and try it, "done fading" prints out, without there having been any fade.

This is because the interpretter evaluates the expression db and then passes the result of that expression as an argument to the Pbind contructor. It is only evaluated that one time. In order to get the current value of db, we need a way to tell the pbind to re-evaluate it every time it comes up. We can do that with Pfunc

Pfunc is a wrapper for functions, so they can be used in patterns. It's constructor takes a function as an argument and then it evaluates that function every time it's asked for a value. Let's re-write our pbind:

 // ...

pbind = Pbind(

\dur,   Pseq([0.2, 0.4, 0.6], inf),
\degree,   Pseq([0, 3, 5, 7, 9, 8, 8, 2].pyramid(1), inf),
\steapsPerOctave, 10,
\db,    Pfunc({db});
);

// ...


Remember that functions return the value of their last line. Since we only have one line, it returns that. And, indeed, the amplitude fades away to quiet. However, the Pbind keeps running even after we can't hear it. We can use an if statement to tell it to stop:

 pbind = Pbind(

\dur,   Pseq([0.2, 0.4, 0.6], inf),
\degree,   Pseq([0, 3, 5, 7, 9, 8, 8, 2].pyramid(1), inf),
\steapsPerOctave, 10,
\db,    Pfunc({
if(db > -72, {
db
}, {
nil
})
})
);


Pbinds stop running as soon as any symbol is paired with nil. Therefore, when db gets to -72 and the Pfunc returns nil, the whole Pbind stops. If the Pbind were in a Pseq, it would go on to the next item.

You may have also noticed that we don't have semicolons everywhere they could be. This is because they separate lines of code, so it's ok to skip them on the last (or only) line in a block of code. It makes no difference to the interpretter if there is a semicolon after nil or not. If you find it easier to use them everywhere, then you should keep doing that.

We could also skip the false function for the if, since it will still return nil if we do:

Pfunc({ if(db > -72, { db }) })

The final version of this example, all together is:

(

db = -12;

// ...

5.wait;

60.do({
db = db - 1;
0.1.wait;
});

});

pbind = Pbind(

\dur,   Pseq([0.2, 0.4, 0.6], inf),
\degree,   Pseq([0, 3, 5, 7, 9, 8, 8, 2].pyramid(1), inf),
\steapsPerOctave, 10,
\db,    Pfunc({ if(db > -72, { db }) })
);

pbind.play;

)


#### Summary

• Decibels can be an easier system to use when computing amplitudes
• Pbinds will convert between db and amp
• The messages ampdb and dbamp can convert number values from amps to db or db to amps
• pyramid is an interesting way of shuffling an array
• You can put a function in a pattern with Pfunc
• A Pfunc with get re-evaluated for every event
• A Pbind stops when it gets a nil value

#### Problem

1. Write a short piece of music where two separate Pbinds both access the same variable. They can be in the same Ppar or not.
2. Write a programme such that one Pbind sets a flag that causes another Pbind to change in some way.

## Saturday, June 05, 2010

### Chords

Now that we can use Pbinds to make sure our sounds come on time, let's look about how to order them and play more than one note at once. The easiest way to do polyphony is with arrays:

Pbind(\note, [1, 3, 5]).play

The Pbind creates a separate synth for each item in the array.

\note determines pitch as a scale degree in an equal tempered scale. It computes the frequency based on the note number and then uses that for the synth's freq argument. \note can be used with any synthdef.

While note is always equally tempered, it need not be 12-tone ET:

(
Pbind(
\note,    [1, 4, 7],
\stepsPerOctave,  10
).play
)


By pairing \stepsPerOctave with 10, the example above gives us 10-tone ET. We could do 24 for a quatertone scale, or use whatever number we'd like.

If, for some reason, we wanted to use MIDI note numbers we could do that. We don't need to use whole numbers, but can use Floats to change the tuning.

Pbind(\midinote, 60.05).play

60.05 is middle C, 5 cents sharp.

### Rests

If we want to rest for a note, we can do that by pairing the symbol \rest to any of the symbols that control pitch:

(
Pbind(
\dur,   0.2,
\note,    Prand([1, 4, 7, 9, \rest], 15),
\stepsPerOctave,  10
).play
)


We could also pair rest with \freq, \midinote, or \degree - which is the degree in the scale.

### Ppar

If we want to play two Pbinds at the same time, just telling one to play right after the other does not guarantee that they will line up perfectly. To make sure they start in sync, we can use Ppar.

Ppar takes two arguments, a list and the number of repeats. Here's an example from the helpfile:

(
var a, b;
a = Pbind(\note, Pseq([7, 4, 0], 4), \dur, Pseq([1, 0.5, 1.5], inf));
b = Pbind(\note, Pseq([5, 10, 12], 4), \dur, 1);
Ppar([a, b ]).play;
)


a and b play exactly in time with each other.

If we don't want all the patterns to start right away, we can use Ptpar, which is the same except that the list contains pairs of times and patterns. Each time is how long to delay before starting the pattern:

(
var a, b;
a = Pbind(\note, Pseq([7, 4, 0], 4), \dur, Pseq([1, 0.5, 1.5], inf));
b = Pbind(\note, Pseq([5, 10, 12], 4), \dur, 1);
Ptpar([ 0.0, a, 1.3, b ], 2).play;
)


Pbind a starts immediately, because it's time is 0. Pbind b starts after 1.3 seconds. The whole thing repeats twice, because of the second argument to Ptpar

If, instead of playing at the same time, we wanted to play one after the other, we can put the Pbinds into a Pseq:

(
var a, b;
a = Pbind(\note, Pseq([7, 4, 0], 2), \dur, Pseq([1, 0.5, 1.5], inf));
b = Pbind(\note, Pseq([5, 10, 12], 2), \dur, 1);
Pseq([a, b ]).play;
)


And Pseqs can be passed to Ppars and Ptpars and vice versa.

#### Summary

• Pairing an array with a symbol in a Pbind makes it play chords
• \note determines pitch as a scale degree in an equal tempered scale and can be use with any synthdef.
• \degree is the degree in the scale
• \stepsPerOctave set the number of pitches in the scale used by \note or \degree
• \midinote is the midinote number - in Floats
• Pairing \rest with any of pitch-related symbols will cause a rest
• We can start two or more Pbinds at the same time with Ppar
• We can start two or more Pbinds with a pre-set delay between them using Ptpar
• We can start two Pbinds sequentially by putting them in a Pseq
• We can put Pseqs in Ppars and vice versa.

#### Problems

1. Write a short A B A (refrain verse refrain) piece with a higher pitched line and a lower pitched line, with their own rythms. You can use the default synth for Pbind or one (or more) of your own.

## Friday, June 04, 2010

### Pbinds

If you've been using tasks to control rhythmic sounds, you may have noticed that sometimes the timing can wander a bit. If you have two separate tasks running at the same time, they can also get out of sync. Tasks don't guarantee exact timing. Also, remember that the language interpreter and the audio server are separate programs. There is a small delay between telling the server to play something and when it actually plays it. It's possible to compensate for this, by giving it instructions slightly ahead of time. Pbinds compensate automatically.

p = Pbind.new.play;

That will repeat forever until you stop it.

p.stop;

A Pbind is a sort of a pattern. Patterns use the information that you provide and make assumptions about the information that you don't. In the above example, we didn't specify anything, so it picked all default values. Let's change the frequency:

Pbind(\freq, 660).play

Pbind.new takes an even number of arguments, as many or as few as you would like. They come in pairs, where the first member is a symbol and the second is an expression. For example:

Pbind(\freq, 660, \dur, 0.2 + 0.3.rand).play

Note that the expressions are evaluated when the Pbind's constructor is called. Therefore, whatever value is returned by 0.2 + 0.3.rand will be the duration for every separate event.

Repeating the same note over and over is rather dull, so there are some patterns that can help.

Prand takes two arguments, an array and the number of times it should run. For example:

(
Pbind(
\freq, Prand([330, 440, 660], 6)
).play
)


When the Pbind is playing, Prand picks a frequency from the array and uses that for the event. The next time, Prand again picks one of the freqs. It does this 6 times. Then the Pbind stops playing.

You can change the number of repeats to any number you would like, including inf. If you have multiple patterns in your Pbind, it will stop with whichever one ends first:

(
Pbind(
\freq, Prand([330, 440, 660], 6),
\dur, Prand([0.2, 0.4, 0.3], 5)
).play
)


That only plays five notes because the second Prand only will return a value 5 times.

You can also play through a list with Pseq:

(
Pbind(
\freq, Pseq([ 1/1, 3/2, 4/3, 9/8, 16/9, 5/4, 8/5 ] * 440, 1),
\dur, Prand([0.2, 0.4, 0.3], inf)
).play
)


Pseq takes three arguments: a list and the number of times that it should play through the entire list. The third argument is an optional offset. Note that in the example, we're multiplying the entire array by 440. Every single element is multiplied, which gives us frequencies in the audible range. Note you can do additional math this way also:

(
Pbind(
\freq, Pseq(([ 1/1, 3/2, 4/3, 9/8, 16/9, 5/4, 8/5 ] * 440) + 10, 1),
\dur, Prand([0.2, 0.4, 0.3], inf)
).play
)


The lists passed to patterns can contain other patterns:

(
Pbind(
\freq, Pseq([ 1/1, 3/2, 4/3, 9/8, 16/9, 5/4, 8/5 ] * 440, inf),
\dur, Pseq([
Pseq([0.2, 0.4], 2),
Pseq([0.3, 0.3, 0.6], 1)
], 3)
).play
)


You can change what synthdef the Pbind is playing with \instrument. First, let's define a synthdef:

(
SynthDef(\example9, {|out = 0, freq, amp, dur, pan = 0, mod = 50|

var pm, modulator, env, panner;

modulator = SinOsc.ar(mod, 0, 0.2);
pm = SinOsc.ar(freq, modulator);

env = EnvGen.kr(Env.perc(0.01, dur, amp), doneAction:2);
panner = Pan2.ar(pm, pan, env);

Out.ar(out, panner);
}).store
)


Then, specify it:

(
Pbind(
\instrument, \example9,
\freq,  Pseq([ 1/1, 3/2, 4/3, 9/8, 16/9, 5/4, 8/5 ] * 440, inf),
\dur,  Pseq([
Pseq([0.2, 0.4], 2),
Pseq([0.3, 0.3, 0.6], 1)
], 3)
).play
)


We can set values for any of the synthdef's arguments:

(
Pbind(
\instrument, \example9,
\mod,  Pwhite(20, 100, inf),
\freq,  Pseq([ 1/1, 3/2, 4/3, 9/8, 16/9, 5/4, 8/5 ] * 440, inf),
\dur,  Pseq([
Pseq([0.2, 0.4], 2),
Pseq([0.3, 0.3, 0.6], 1)
], 3)
).play
)


Pwhite takes three arguments, a low number, a high number and the number of times to run. It then picks random numbers between the low and high values. In the example, we use those to control the modulation frequency of our synthdef.

Some argument names for synthdefs are quite common, like: amp, freq, pan, and out. Pbinds expect to see those argument names and will provide reasonable values if you don't specify. If you have a more original name for an argument, it's a good idea to specify values for it in the Pbind.

(
SynthDef(\example9a, {|out = 0, freq, amp, dur, pan = 0, mod = 50, modulation_depth = 0.2|

var pm, modulator, env, panner;

modulator = SinOsc.ar(mod, 0, modulation_depth);
pm = SinOsc.ar(freq, modulator);

env = EnvGen.kr(Env.perc(0.01, dur, amp), doneAction:2);
panner = Pan2.ar(pm, pan, env);

Out.ar(out, panner);
}).store
)

(
Pbind(
\instrument, \example9a,
\modulation_depth,
0.3,
\mod,  Pwhite(20, 100, inf),
\freq,  Pseq([ 1/1, 3/2, 4/3, 9/8, 16/9, 5/4, 8/5 ] * 440, inf),
\dur,  Pseq([
Pseq([0.2, 0.4], 2),
Pseq([0.3, 0.3, 0.6], 1)
], 3)
).play
)


Do not assume that your default values from your synthdef will be used. If you want it to always be a certain value, specify that value.

#### Summary

• Pbinds are more accurate than Tasks for playing in time.
• Pbinds assume several default values, which you can specify if you want to change them.
• Prand(list, n) picks an item from the given list n times.
• Pseq(list, n) plays the entire list n times.
• If you do a math operation with a SimpleNumber and an array, it does the operation for each item of the array and stores the result in an array.
• Pseqs can contain other patterns, including other Pseqs
• You can specify what synthdef to play with \instrument
• Pwhite(lo, hi, n) picks a number between low and high n times
• Symbols in a Pbind can correspond to synthdef argument names
• If you have an unusual argument name, it's a good idea to specify a value for it in the Pbind

## Monday, May 31, 2010

### Arrays

As you've heard many times, a list surrounded by square brackets is an Array. Specifically, it's a comma delineated list of 0 or more elements. Here are some examples:

[1]
[x, y, z]
["in", "the", "house"]
[]


There is often more than one way to do something in SuperCollider, as in life. We can also create an Array by using a constructor. The constructor takes one argument, the size of the array.

a = Array.new(size);


Arrays can hold any kind of object, including numbers, variables, strings or nothing at all. They can even mix types:

[3, "French hens", 2 "turtledoves", 1 "partridge"]


Arrays can even hold other arrays:

[[1, 2, 3], [4, 5, 6]]


You can also put an expression in an array. The interpreter evaluates it and stores the results. So [ 3 - 1, 4 + 3, 2 * 6] is also a valid array, stored as [2, 7, 12]. [x.foo(2), x.bar(3)] is also an array. It passes those messages to the objects and puts the result into the array. Because commas have extremely low precedence, they get evaluated after the expressions they separate.

A variable can be part of an expression that is put into an array:

(
var foo, bar;
...
[foo + 1 , bar];
)


In that last case, it holds the value of the expressions (including the variables) at the time they became part of the array. For example:

(
var foo, arr;
foo = 2;
arr = [foo];
arr.postln;
foo. postln;

" ".postln;

foo = foo + 1;
arr.postln;
foo. postln;
)


Outputs:

[ 2 ]
2

[ 2 ]
3
3


This is almost just what we expected. From whence did the second 3 at the bottom come? SuperCollider's interpreter prints out a return value for every code block that it runs. bar was the last object in the code block, so bar gets returned. bar's value is 3.

The variables can go on to change, but the array holds the value that was put in, like a snapshot of when the expression was evaluated.

What if we declare a five element array and want to add something to the array? We use the Array.add message.

(
var arr, new_arr;
arr = ["Mary", "had", "a", "little"];
arr.postln;
new_arr.postln;
)


Outputs:

[ Mary, had, a, little ]
[ Mary, had, a, little, lamb ]


Arrays cannot grow in size once they've been created. So, as stated in the helpfile, “the 'add' method may or may not return the same Array object. It will add the argument to the receiver if there is space, otherwise it returns a new Array object with the argument added.” Therefore, when you add something to an array, you need to assign the result to a variable. arr doesn’t change in the example because it is already full.

There are other messages you can send to Arrays, which are detailed in the Array helpfile and the helpfile for its superclass ArrayedCollection. Two of my favorite are scramble and choose.

The helpfile says that scramble "returns a new Array whose elements have been scrambled. The receiver is unchanged."

The results of scramble are different each time you run it, because it scrambles in random order. When it says, "the receiver is unchanged", it means that if we want to save the scrambled Array, we have to assign that output to a new variable. The receiver is the object that receives the message "scramble." In the following example, the receiver is arr, which contains [1, 2, 3, 4, 5, 6].

(
var arr, scrambled;
arr = [1, 2, 3, 4, 5, 6];
scrambled = arr.scramble;
arr.postln;
scrambled.postln;
)


For me, this output:

[ 1, 2, 3, 4, 5, 6 ]
[ 4, 1, 2, 3, 6, 5 ]


Of course, the second array is different every time. But arr is always unchanged.

Choose is similar. It picks a random element of the Array and outputs it. The receiver is unchanged.

[1, 2, 3].choose.postln;


Will output 1, 2 or 3 when you run it.

Arrays are lists, but they are not merely lists. They are indexed lists. You can ask what the value of an item in an array is at a particular position.

(
var arr;
arr = ["Mary", "had", "a", "little"];

arr.at(1).postln;
arr.at(3).postln;
)


Outputs:

had
little


Array indexes in SuperCollider start with 0. In the above example, arr.at(0) is "Mary".

You can also put the index number in square brackets. arr[0] is the same as arr.at(0). If you are using square brackets, you can also modify the contents of the array:

(
var arr;
arr = ["Mary", "had", "a", "little", "lamb"];

arr[4] = "giraffe";
arr.postln;
)


Arrays also understand the message do, but treat it a bit differently than an Integer does.

(
[3, 4, 5].do ({ arg item, index;
("index: " ++ index ++ " item: " ++ item).postln;
});
)


Outputs:

index: 0 item: 3
index: 1 item: 4
index: 2 item: 5


We've called our arguments in this example item and index, but they can have any name we want. It doesn't matter what we call them. The first one always gets the value of the array item that the loop is on and the second one always gets the index.

The ++ means concatenate, by the way. You use it to add something to the end of a string or an array. For example:

"foo " ++ 3 returns the string "foo 3"

With arrays, you can use it to add a single item or another array:

(
var arr1, arr2, arr3;

arr1 = [1, 2, 3];
arr2 = arr1 ++ 4;
arr3 = arr2 ++ [5, 6];

arr1.postln;
arr2.postln;
arr3.postln;
)


Outputs

[ 1, 2, 3 ]
[ 1, 2, 3, 4 ]
[ 1, 2, 3, 4, 5, 6 ]


Note that the receiver is unchanged.

Size is a message which gives us the size of the array. This can be useful, for example, if we have a variable that we want to use as an index, but which might get bigger than the array:

arr.at(index % arr.size);


Remember that the modulus (%) gives us a remainder. This means that if the count gets to be greater than the number of elements in the array, using a modulus will cause it to wrap around to zero when it exceeds the size of the array. There is also a message you can send to arrays that does this for you:

arr.wrapAt(index);

It does the modulus for you.

#### Musical Example

In a previous post, I mentioned Nicole, the ex-grad student working at a SuperCollider startup. Since then, she's gotten another assignment from her boss. She has to write a function that takes as arguments: an array of tuning ratios, a base frequency and a detuning amount. It has to figure out the final pitches by first multiplying the base frequency by the ratio and then adding the detuning amount to the result. It should then play out the resulting scale.

She's created SynthDef:

(
SynthDef(\example8, {|out = 0, freq, amp, dur, pan = 0|

var pm, modulator, env, panner;

modulator = SinOsc.ar(50, 0, 0.2);
pm = SinOsc.ar(freq, modulator);

env = EnvGen.kr(Env.perc(0.01, dur, amp), doneAction:2);
panner = Pan2.ar(pm, pan, env);

Out.ar(out, panner);
}).store
)


Since she's been working in the field, she's learned that instead of writing "arg" followed by a list or arguments and then a semicolon, she can just put all her arguments between two vertical bars. The two versions are exactly identical.

In the synthdef, one of the SinOscs is modulating the phase of the other SinOsc.

After learning about Arrays, our hero does a bit of research on tuning ratios and comes up with an array of ratios that she will use to test her function. It looks like: [ 1/1, 3/2, 4/3, 9/8, 16/9, 5/4, 8/5 ]

That is 1 divided by 1, 3 divided by 2, four divided by 3, etc. Now remember that precedence means that the interpreter evaluates things in a particular order. It looks at / before it looks at commas. So it seems a bunch of /'s and starts dividing. Then it looks at the commas and treats it as an array. The interpreter stores that array as:

[ 1, 1.5, 1.3333333333333, 1.125, 1.7777777777778, 1.25, 1.6 ]

Nicole's function will contain a task which cycles through the ratios, taking each one and multiplying it by the base frequency and adding the detuning amount. Remember that SuperCollider is like a cheap calculator and +, -, *, and / all have the same precedence. Math is evaluated from left to right. So ratio * baseFreq + detune is not equivalent to detune + ratio * baseFreq, like it would be in algebra. However, fortunately, she can use parenthesis like we would in algebra.

She could write out her expression as (ratio * baseFreq) + detune or (detune + (ratio * baseFreq)) or in many other ways. Even though she could get the right answer without using parenthesis at all, it's good programming practice to use them.

Nicole has a formula and she has an Array. She just needs a way to step through it. Fortunately, she knows that the 'do' method also exists for Arrays.

She writes her code as follows:


(

var func, arr;

func = { |ratio_arr, baseFreq = 440, detune = 10, dur  = 0.2|
var freq;

ratio_arr.do({ |ratio, index|
freq =  (ratio * baseFreq) + detune;
Synth(\example8, [\out, 0, \freq, freq, \amp, 0.2, \dur, dur,
\pan, 0]);
dur.wait;
});
});
};

arr = [ 1/1, 3/2, 4/3, 9/8, 16/9, 5/4, 8/5];

func.value(arr, 440, 10).play;
)


This is pretty cool, but it always plays out in the same order, so she changes her do loop to: ratio_arr.scramble.do({ |ratio, index|

#### Summary

• You can declare an array by putting a list in square brackets or by using the constructor Array(size)
• Arrays can hold any types of objects, all mixed together
• You can put an expression into an array. It will hold the result of evaluating the expression.
• You can add items to an array by using the add message
• The scramble message returns a new array which has the same contents as the receiver, but in a random order
• The choose message will return a single element of the receiver, chosen at random
• You can access elements of an array with their index: arr.at(index) or arr[index]
• You can modify a single element of an array with the index: arr[index] = foo
• You can loop through an array with do: arr.do({|item, index|
• ++ can be used to concatenate strings or arrays
• arr.size returns the size of the array
• In order to make sure your index is not larger than the size of the array, you can use modulus or wrapAt: arr[index % arr.size] or arr.wrapAt(index)
• arguments can be listed inside vertical bars instead of after the word arg: |arg1, arg2| is the same as arg arg1, arg2;

#### Problems

1. You can navigate arrays of different length using variables for indexes.
2. (

var arr1, arr2, index;

arr1 = [1, 2, 3];
arr2 = [3, 4, 5, 6];
index = 0;

2.do({
arr1.do({ arg item;
("arr1 " ++ item).postln;
("\t arr2 " ++ arr2.wrapAt(index)).postln; //"\t" means tab
index = index + 1;
});
});
)

Use this idea to create duration, pitch and wait loops of different lengths. Write a task to pay them
3. In the previous post, there was an example that used if statements to control adding to or subtracting from the frequency. Instead of changing the frequency directly, change an index that will access an array of tuning ratios.

## Sunday, May 30, 2010

### While

We’ve used Boolean expressions to control the flow of execution of a program with if. Another control structure is while. While is a message passed to a function. The function must return either true or false. It is a test function. There is another function passed in as an argument. test_function.while(loop_function); If the test function is true, the loop function gets run. Then the test function is run again. If it returns true again, the loop function is run again. This continues until the test function returns false. While the condition is true, the loop is executed.

(
var counter;

counter = 0;

{counter < 6}.while ({

counter = counter + 3.rand;
counter.postln;

})
)


{counter < 6} is the test function. If it is true, we run the next two lines inside the while loop.

counter = counter + 3.rand; adds the result of 3.rand to the variable counter and then stores the result of that in the variable counter. Recall that in assignment statements (statements where variables get a value), there can only be one thing on the left of the equals sign. Everything to the right is evaluated and then result of that evaluation is assigned to the variable. It's ok to have the same variable on both sides of the equal sign. The value of the variable does not change until everything has already been evaluated.

If instead of counter = 0; we had counter = 7; the test function would have run once, but the loop function would not have run at all.

As with if, functional notation is also common with while. Remember that both notations are entirely equivalent. The following two lines are the same:

test_func.while(loop_func);
while(test_func, loop_func);


Let's have a musical example, where we track elapsed time rather than the number of notes played. First, we need a synthdef:

(
SynthDef(\example7, {arg out = 0, freq = 440, dur = 1, amp = 0.2, pan = 0;

var env, form, panner;

env = EnvGen.kr(Env.perc(0.01, dur, amp), doneAction:2);
form = Formant.ar(freq, freq + 100, freq + 245);
panner = Pan2.ar(form, pan, env);

Out.ar(out, panner);
)


Formant is an oscillator that creates formants. You can find out more about it in it's helpfile.

Pan2 is a two channel panner which takes three arguments: the signal, the position and the amplitude. The position can vary from -1 to 1 and 0 is in the center.


(

var freq, dur, total_dur, count;

dur = 0.17;
total_dur = 0;
count = 0;

{total_dur < 20}.while({

freq = 400;

(count % 3 == 0).if({
freq = freq + 200;
});
(count % 4 == 0).if({
freq = freq - 100;
});
(count % 5 == 0).if({
freq = freq + 400;
});

Synth(\example7, [\out, 0, \freq, freq, \dur, dur, \amp, 0.2, \pan, 0.7.rand2]);

count = count + 1;
total_dur = total_dur + dur;
dur.wait;
});
}).play
)


(This code is translated to SuperCollider from a tutorial for making music with Perl.)

At the start, we declare our variables and then we initialise them. This is an important step, because before we assign them a value, they start out with the value nil. Nil is not meaningful with a <, nor with any other mathematical or boolean operation.

In our test function, we see if the elapsed duration is less than 20 seconds.

Then in our loop, we add and subtract from a given frequency based on the divisors of a counter.

rand2 is a message that can be passed to numbers. It returns a random result between (-1 * this) and this. So 0.7.rand returns a number between -0.7 and 0.7. This will cause our sound to random pan from left of center to right of center.

After we play the synth, we update all our variables. If we forget to add the dur to the total_dur, the test function will always return true and we will never leave the loop. I sometimes forget this, as it's a common bug.

The next example is very similar to one from the previous post.

(
SynthDef("example7b", {arg out = 0, freq = 440, amp = 0.1,
dur = 1, pan = 0;

var blip, env, panner;

env = EnvGen.kr(Env.triangle(dur, 1), doneAction:2);
blip = Blip.ar(freq, env * 3);
panner = Pan2.ar(blip, pan, env * amp);
Out.ar(out, panner);
)

(
var freq, synth_dur, high_freq;

high_freq = 800;

while({high_freq > 0}, {

freq = 200 + high_freq.rand;
if((freq >= 600), {
synth_dur = 0.1 + 1.0.rand;
} , {
if ((freq <= 400), {
synth_dur = 1 + 5.0.rand;
},{
synth_dur = 0.1+ 2.0.rand;
});
});
Synth(\example7b, [\out, 0, \amp, 0.1, \freq, freq,
\dur, synth_dur, \pan, 0.8.rand2]);

high_freq = high_freq - 50.rand;
(0.01 + 0.4.rand).wait;
});
}).play;
)


Because we keep subtracting from high_freq, the highest possible frequency is tending downwards. We keep subtracting until it gets to zero. Incidentally, changing allowable ranges of parameters over time is called tendency masking.

There are other Control Structures detailed in a help file called Control-Structures. Highlight "Control-Structures" and press shift-d

#### Summary

• While is a control structure that controls a loop
• The test condition for while is a function which returns a boolean. While is a message passed to that function. It takes a function as an argument.

#### Problems

• It is allowable to have two or more tasks going at the same time. Write a programme that has two tasks, one playing notes tending upwards ans the other downwards.
• Make it such that when one while stops, the other does also. You may find it helpful if there is a variable that they both can access.

## Saturday, May 29, 2010

### Boolean Expressions

Last time, we learned to randomly pick true or false values, however, it would be more useful if we could test to see what's going on and make decisions according to those tests. Fortunately, we can do that with boolean expressions.

An expression is a bit of code that can be evaluated. 2+3 is an expression, who's value is 5. A boolean expression is an expression that results in a boolean. Boolean expressions are usually tests. For example, we can test for equivalency with ==

(
a = 3;
if (a == 3, {
"true".postln;
}, {
"false".postln;
});
)


Note that is two equal signs next to each other when we're testing for equivalency. If you just use one equal sign, it means assignment. I often accidentally type one equals sign when I mean to type two.

We can test for greater than or less than:

(
a = 3;
if (a > 4, {
"true".postln;
}, {
"false".postln;
});
)

(
a = 3;
if (a < 4, {
"true".postln;
}, {
"false".postln;
});
)


We can also test for greater than or equals to and less than or equals to:

(
a = 4;
if (a >= 4, {
"true".postln;
}, {
"false".postln;
});
)

(
a = 3;
if (a <= 4, {
"true".postln;
}, {
"false".postln;
});
)


We can also do boolean operations. Some of the most important ones are not, and, and or.

The easiest way to illustrate these is with truth tables. A truth table shows you all possible combinations of true and false variables and what the results would be. Any Boolean variable can be either true or false. This is a truth table for not:

not
truefalse
falsetrue

Not is a unary operator. That means it only involves one object. The top of the table shows a true input and a false input. The bottom of the table shows the result. true.not returns false and false.not returns true.

And is a binary operator. Like +, -, *, / and %, it operates on two objects. Lets’ say we have two variables, a and b, and either of them can be true or false. We can put a along the top of the table and b down the left side. In the middle we put the possible results of a and b.

and
truefalse
truetruefalse
falsefalsefalse

Or is also binary:

or
truefalse
truetruetrue
falsetruefalse

So how do we code these? Let’s look again at not. Not can be a message sent to a boolean or boolean expression:

(
if ((a==4).not , {
"true".postln;
}, {
"false".postln;
});
)


You can combine not and equivalency with not equals: !=

(
a = 2;

if (a != 4 , {
"true".postln;
}, {
"false".postln;
});
)


The last two examples are the same.

And is represented by &&

(
a = 3;
b = 4;

if ( (a > 2) && (b < 5), {
"true".postln;
}, {
"false".postln;
});
)


Both (a > 2) and (b < 5) must be true for this expression to evaluate as true. If one of them is false, the whole thing is false.

Or is represented by || (Those are vertical lines. If you have a Macintosh with an American keyboard, they're over the slash \)

(
a = 3;
b = 4;

if ( (a > 2) || (b < 5), {
"true".postln;
}, {
"false".postln;
});
)

(
a = 3;
b = 4;

if ( (a < 2) || (b < 5), {
"true".postln;
}, {
"false".postln;
});
)

(
a = 3;
b = 4;

if ( (a > 2) || (b == 5), {
"true".postln;
}, {
"false".postln;
});
)


For these expressions to evaluate to true, only one part of it needs to be true. If neither part of an or is true, then the whole thing is false.

#### Musical Example

Let's have a musical example. We'll again generate random pitches, but low pitches will have long durations and high ones will be short. First, we need a SynthDef:

(
SynthDef("example6", {arg out = 0, freq = 440, amp = 0.1,
dur = 1;

var blip, env_gen, env;

env = Env.triangle(dur, 1);
env_gen = EnvGen.kr(env, doneAction:2);
blip = Blip.ar(freq, env_gen * 3, env_gen * amp);
Out.ar(out, blip);
)


We're trying out a new oscillator called Blip. The helpfile for it says:

Band Limited ImPulse generator. All harmonics have equal amplitude. This is the equivalent of 'buzz' in MusicN languages.

WARNING: This waveform in its raw form could be damaging to your ears at high amplitudes or for long periods.

The first argument is the frequency. The second is the number of harmonics, which is to say the number of overtones and the third is amplitude. Loud tones with lots of harmonics can hurt our ears! So let's watch out. I suspect anyhting that's bad for ears is probably also bad for speakers.

We're going to control the number of harmonics with the envelope, so they change over time. We're using the same envelope for amplitude as we are for harmonics, so env_gen * 3 gives us a maximum of 3 harmoics at the peak. If you want more or less, you can change that number. And, of course, env_gen * amp gives us an envelope that goes from 0 to the amp passed in as an argument.

Ok, now for the Task that will play this


(
var freq, synth_dur;
50.do({
freq = 200 + 800.rand;
if((freq >= 600), {
synth_dur = 0.1 + 1.0.rand;
} , {
if ((freq <= 400), {
synth_dur = 1 + 5.0.rand;
},{
synth_dur = 0.1+ 2.0.rand;
});
});
Synth(\example6, [\out, 0, \amp, 0.05, \freq, freq,
\dur, synth_dur]);
(0.01 + 0.4.rand).wait;
});
}).play;
)


Ok, in our first if statement, we test for frequencies that are greater than or equal to 600 Hz. If they are that high, then we set our variable synth_dur to 0.1 + 1.0.rand. If the freq is not that high, we go to the false function. In the false function, we find another if statement. In this if statement, we test for frequencies that are less than or equal to 400 Hz. If they are that low, then we set our variable synth_dur to 1 + 5.0.rand. the the freq is not that low, we go to the false condition and set our variable synth_dur to 0.1+ 2.0.rand. We only get to that second false function if both true functions are false. We could re-write those test conditions:

    if((freq >= 600), {
synth_dur = 0.1 + 1.0.rand;
});
if ((freq <= 400), {
synth_dur = 1 + 5.0.rand;
});
if ((freq < 600) && (freq > 400), {
synth_dur = 0.1+ 2.0.rand;
});


The result would be the same. But if we do it that way, we have to go through three if statements every time through the loop. If we do it with nested if statements as above, we only have to go through two of them at most. And, if the frequency is high, we only need to go through the first one. So the nested if statements are slightly more efficient, however, it's good to figure out exactly what conditions would have to be to get to a particular code block.

#### Summary

• An expression is a snippet of code that has a value or can return a value
• You can test for equivalency with ==
• Greater than is >
• Less than is <
• Greater than or equal to is >=
• Less than or equal to is <=
• Not is boolean.not and causes things to invert
• Not equals is !=
• And is &&. Both conditions must be true for and to be true.
• Or is ||. One or both conditions must be true for or to be true.
• If statements can be nested

#### Problems

• Write if statements using and, or, and not using Boolean values of true and false to illustrate the truth tables, using all possible combinations of true and false. For example:
(
if (true.not, {
"true".postln;
}, {
"false".postln;
});
)

What do you expect each of them to print? Did the results you got from running them match your expectations?
• ## Friday, May 28, 2010

### If

In our programmes, we need control structures, that is, ways to make decisions. One control structure is if. if has it's own helpfile. Highlight if and press apple-d. If is also explained briefly in the helpfile for Boolean.

A Boolean is a value that is either true or false. true and false are reserved words in SuperCollider. We can send an if message to Booleans.

(
([true, false].choose).if(
{
"true".postln;
}, {
"false".postln;
}
);
)


Remember that a list surrounded by square brackets is an Array. Arrays understand a message called choose. It randomly picks an item in the array and returns it.

If you run the above code several times, “true” and “false” should print out about the same number of times in a random order, because [true, false].choose ought to be true half the time and false the other half. The result of that expression is a Boolean. We send an if message to the Boolean, which has two arguments, both functions. The first function is evaluated if the Boolean is true. The second function is evaluated if the Boolean is false.

boolean.if(trueFunction, falseFunction);

You can omit the false function if you want.

This syntax that we've been using, object.message(argument1, argument2, . . . argumentN);, is the most commonly used syntax in SuperCollider programs. It's called receiver notation. However, there is more than one correct syntax in SuperCollider. There also exists a syntax called functional notation. It is more commonly used with if messages than receiver notation. When you see if in the helpfiles, the examples almost always use functional notation. Functional notation is:

message(object, argument1, argument2,  . . . argumentN);

The two notations are equivalent. You can replace one with the other at any place in any program and it will not change the program. The reason that I bring this up is that people very commonly use functional notation for if:

if(boolean, trueFunc, falseFunc);

So our example would change to:

(
if([true, false].choose, {
"true".postln;
}, {
"false".postln;
});
)


It works in exactly the same way.

Why are there multiple correct notations? It's confusing!

SuperCollider is based on many other programming languages, but the language that it borrows most heavily on is one called Smalltalk. Smalltalk, like SuperCollider, is an object-oriented language. When I took Programming Languages at uni, my teacher said that Smalltalk was the best object oriented language and the only reason it wasn't the most popular was that the syntax was insane.

So rather than force us to use Smalltalk syntax, James McCartney, the author of SuperCollider, allows us multiple legal syntaxes. Receiver notation is common in several object-oriented languages. Functional notation, however, persists in if, probably because other languages have different ways of thinking about if.

Let's code an overtone player that has a 50% chance of resting. First, we need a synthdef:

(
SynthDef.new("example5", {arg out = 0, freq = 440, amp = 0.2,
dur = 1;

var saw, env_gen, env;

env = Env.triangle(dur, amp);
env_gen = EnvGen.kr(env, doneAction:2);
saw = Saw.ar(freq, env_gen);
Out.ar(out, saw);
)


This one uses a sawtooth wave oscillator. Check out the helpfile for Saw for more information.

Then, our player:

(
var player;

player = { arg baseFreq, numOvertones, dur = 0.2;
var freq;
(numOvertones + 1).do({ arg index;
freq = index * baseFreq;
if ([true, false].choose, {
Synth(\example5, [\out, 0, \freq, freq, \dur, dur]);
});
dur.wait;
});
});
};

player.value(220, 12).play;
)


If you run it several times, it should rest in different spots, about half the time.

If we want to give it a 33.3% chance of resting (a 66% chance of playing), we could change out if to look like [true, true, false].choose and expand our array every time we want to change the probability. But what if we want something to play 99% of the time? We would have to have 99 trues and one false. Fortunately, there is a message you can use that returns a Boolean based on percentage. To play 99% of the time, we would use 0.99.coin

If you look at the helpfile for float, you learn that coin, "answers a Boolean which is the result of a random test whose probability of success in a range from zero to one is this." Which means that 0.66.coin has a 66% chance of being true and 0.01.coin has a 1% chance of being true.

The word "this" in that description refers to the number which received the message. If you type 0.66.coin, "this" is 0.66.

Let's give our an example 75% chance of playing a given note:

(
var player;

player = { arg baseFreq, numOvertones, dur = 0.2;
var freq;
(numOvertones + 1).do({ arg index;
freq = index * baseFreq;
if (0.75.coin, {
Synth(\example5, [\out, 0, \freq, freq, \dur, dur]);
});
dur.wait;
});
});
};

player.value(220, 12).play;
)


#### Summary

• Booleans are either true or false
• if is a way of controlling programme flow and making decisions