tag:blogger.com,1999:blog-106683792024-03-05T10:16:34.826-05:00How to Program in SuperColliderA very rarely updated guide to Supercollider programming.Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.comBlogger30125tag:blogger.com,1999:blog-10668379.post-62157706953140041702015-04-25T09:47:00.000-04:002015-04-25T09:47:40.279-04:00How to keep an installation running on a Raspberry Pi<p>Previously, I covered, <a href="http://sc3howto.blogspot.com/2014/05/how-to-keep-installation-running.html">how to keep an installation running</a>. In that post, I wrote about how anything could crash. The Pi is much the same, except everything <b>will</b> crash at some point.</p><p>I have been working with SC3.6 (<a href="http://celesteh.blogspot.co.uk/2014/04/building-supercollider-36-on-raspberry.html">see these build instructions</a>), but this should also be applicable to any other versions of SuperCollider. This is written for Raspbian Wheezy but should work with other versions of Raspbian. It will not work with other Pi operating systems, such as windows, without substantial modifications, especially to the Bash Script</p><p>There are a few important differences between running an installation on a laptop and on a Pi. <br />
<ul><li>The Pi has fewer resources and crashes much more often and in more ways. <br />
<li>The SC server is started separately from sclang<br />
<li>Backing up a Pi system is just duplicating an SD card, so anything weird or dangerous you do is much less risky than it would be on your laptop<br />
</ul><h3>Getting the Pi Ready</h3><p>Are you planning on attaching a monitor to the Pi? If so, you will want to tell to boot to the desktop. Otherwise, you want to boot to a command line. You can set these options by running <code>sudo raspi-config</code>. My only experience thus far is with the desktop, because I am also generating some simple graphics. Otherwise, I would definitely boot to the command line. The Pi does not have a lot of processor power and if you're not using the Desktop, you can save some space for installation to run.</p><h3>Getting your code ready</h3><h4>Efficiency</h4><p>SC 3.6 on a Pi runs exactly the same code as SC 3.6 on my laptop. Therefore, installation-ready code <i>should</i> run fine on a Pi. There is less memory on a Pi, which may limit the number of Buffers you can have loaded at one time. I have not experienced any issues with running out of memory. The processor, however, does climb to 100% quite easily and this can lead to audio stuttering. Your synthdefs and invocation should be as efficient as possible. If you always fire off three synths at the same time, say, each with a different frequency, you may want to combine them into one single synthdef that takes three frequency arguments. Starting off one more complicated synthdef requires fewer resources than three simpler synthdefs running at the same time.</p><p>If you are running the the desktop, you can see how much of the CPU is being used by looking at the monitor box in the upper right hand corner of the screen. If you are running headless and have connected to the Pi via ssh, you can monitor the CPU using the command 'top'. Open a second terminal window, connect to the Pi and type in <code>top -u pi</code> at the command line. The program will tell you the computer's load average and how much of the CPU each program is using.</p><p>Within SuperCollider, to find out how much CPU the server is using, <code>Server.default.avgCPU</code> returns a number between 0 and 100. I've used this information to help calculate how many steps to use for a fade in the graphics. A busier CPU means I fade in fewer steps with longer pauses between steps.</p><h4>Starting the server separately</h4><p>This is a constraint imposed by <a href="http://celesteh.blogspot.co.uk/2014/04/building-supercollider-36-on-raspberry.html">the build instructions for 3.6</a>. Right now, we're just going to discuss how this changes our SC code. Fortunately, very little needs changing. Use the same code for booting the server as was <a href="http://sc3howto.blogspot.co.uk/">covered in the previous tutorial</a>. The error checking is still useful - even if the server is actually already booted.</p><p>As the server is actually started outside SuperCollider, the port number for the server can (and will) change. We will tell SuperCollider about the port number via command line arguments - we will tell our program about the port number when we start running it. The arguments will be available to our program in an array: <code>thisProcess.argv</code>. Arguments to our program start at index 0. We need to get this data before we do anything involving the server.</p><pre><code>
(
var server_port;
// ...
if ((thisProcess.argv.size > 0), {
server_port = thisProcess.argv[0];
Server.default = Server(\Raspberry, NetAddr("localhost", server_port.asInteger));
s = Server.default;
})
// ... Boot or s.waitForBoot only after the above
)
</code></pre><p>We start by checking if we received any arguments. If the argv.size is 0, then we did not. This means we can still use the same code in the IDE on our regular computer.</p><p>The first argument is the very first thing in argv. If there are subsequent arguments, they will also be in argv, in the order they were given.</p><p>We create a new server object, called Raspberry, that uses the port we've been given as an argument. Note that we also convert the port to an integer, from a string.</p><p>Our new Server object will be our default server, which we also assign to the global s variable. This means everything will work as normal, even on an arbitrary port.</p><h3>The Bash scripts</h3><p>Previously, we used a bash script instead of an IDE. We are going to do that again, but now our script is going to do a few extra things - only if we're on a Pi.</p><p>Bash scripts always start out with #! at the top of the file. After that line, from then on, anything after a # character is a comment, like anything after // in SuperCollider.</p><p>The SuperCollider directory on Pi is either /usr/bin or us/local/bin. to find out which, type <code>which sclang</code> at the command line. If yours is different than the code below, you will need to change it.</p><pre><code>
#!/bin/bash
port=57110
sleep 20
while true
do
#are we on a raspberry pi?
if [ -f /etc/rpi-issue ]
then
# we need these two lines in order to make sound
export SC_JACK_DEFAULT_INPUTS="system"
export SC_JACK_DEFAULT_OUTPUTS="system"
# get rid of anything already running
killall scsynth
sleep 2
killall jackd
# wait for things to settle down
sleep 20
# start jackd
( jackd -T -p 32 -d alsa -d hw:0,0 -r 44100 -p 1024 -n3 -s || sudo shutdown -r now ) &
#wait for jack to settle down
sleep 10
# make sure we increment the port every loop
port=$(( $port + 1))
# start the server
/usr/local/bin/scsynth -u $port & # check supercollider's directory!
server=$!
sleep 1
# is the server running?
if kill -0 $server 2> /dev/null
then
#all good
echo "started"
else
# try again
sleep 5
port=$(( $port + 1 ))
/usr/local/bin/scsynth -u $port & # check supercollider's directory!
server=$!
sleep 1
# is the server running?
if kill -0 $server 2> /dev/null
then
#all good
echo "started"
else
sudo shutdown -r now
fi
fi
sleep 5
# is the server still running?
if kill -0 $server 2> /dev/null
then
#all good
echo "still going"
else
sudo shutdown -r now
fi
/usr/local/sclang installation.scd $port # check supercollider's directory!
else
/path/to/sclang installation.scd #SuperCollider on your normal computer
fi
sleep 1
killall scsynth
sleep 1
done
</code>
</pre>
<p>This script is a lot more complex than the last one! This is because more things can go wrong, alas.</p><p>We start by initialising a variable and then sleeping for 20 seconds before doing anything. The sleep is there at the start because we are going to start the script whenever the Pi boots. The 20 seconds of waiting around gives time for services to start, like the internet connection, if we have one. Also, it gives us time to open a terminal or a connection and type <code>killall installation.sh</code> if we don't want the installation to actually run.</p><p>Then we test if we're on a Pi, by looking to see if a Raspbian-specific file exists. If we are on a Pi, we set two variables that SC3.6 needs set in order to make sound.</p><p>Then we kill any servers or versions of jack left running, possibly from previous times through the loop. Then we sleep for 20 more seconds. The Pi is not a fast computer and this gives the system time to settle down after killing jackd, which is the audio server (like CoreAudio) used on Raspbian.</p><p>Then we try to start jack up again and run it in the background. If it does not start, we reboot the computer. The default user on a Pi is called 'pi'. By default, that user can sudo without entering a password. We are taking advantage of that to make the system reboot. On a normal computer, it would be risky to leave an installation running that could get superuser privileges so easily. However, the Pi's system is just an SD card, which hopefully we have a spare copy of. If something goes horribly wrong, we can just pop in a new card.</p><p>We will configure the Pi so the script runs on startup. This means if the computer reboots, the installation will restart.</p><p>Then we wait 10 seconds for jack to settle down.</p><p>We then increment the port number. In my testing, many crashes are caused by the server crashing. When it crashes, it may not let go of the port it was using. By incrementing every time, we are less likely to have trouble starting the server.</p><p>Then we start the server, wait 1 second and check if it's running. If it's not running, we wait 5 seconds, increment the port and try again. If the second attempt fails, we reboot.</p><p>Then we wait five more seconds and check AGAIN if the server is running. This may seem like overkill, but, unfortunately, the system can get into a state where a server will start, but then crash about 2 seconds later. By waiting five seconds, we can make sure the server will actually stay started. If not, we reboot.</p><p>Then, finally, we start running the installation program!</p><p>Below that, we have an else and the invocation we would use on our other computer. Obviously, this example is slightly silly, as it would make more sense in this case just to have two different scripts. However, if you have helper apps or have to move files around before starting, etc, it can make sense to use the same script for two different systems.</p><h4>Using helper scripts</h4><p>If you have a helper script working in the background, it's going to take up some of the processor power of the Pi. However, if you don't mind it running more slowly, you can tell it to use less power. There is a unix command called <code>nice</code>, which you can use when starting your helper script. You give it a number saying how nice a process should be, ranging from -20 to 19. A high number is a very nice process - it becomes more and more sharing (and runs more and more slowly). A negative number is less and less nice. For our installation, we will tell helper scripts to be more nice, but we'll leave sclang and scsynth running normally. (You might want to experiment with making them less nice. I have avoided this out of worry it would interfere with my debugging process.)</p><p>You would alter your script to add:</p><pre><code>
nice -n 10 /path/to/helper/script.sh &
helperpid=$!
sleep 1
/usr/local/sclang installation.scd $port # check supercollider's directory!
sleep 1
killall scsynth
kill $helperpid
</code>
</pre><h5>Changing the order</h5><p>What if you want to start the helper script <i>after</i> sclang? We still would want to base the loop on when sclang crashes. Fortunately, we can tell a loop to wait for something to stop (read: crash).</p><pre><code>
/usr/local/sclang installation.scd $port &# check supercollider's directory!
scpid=$!
sleep 1 # if you want to pause, otherwise, skip this line
nice -n 10 /path/to/helper/script.sh &
helperpid=$!
wait $scpid
sleep 1
killall scsynth
kill $helperpid
</code>
</pre><h4>Writing Files</h4><p>To write or not to write? We might want to write files for a few reasons. Perhaps we have a helper script that doesn't understand OSC, or the data we want to pass is particularly large, or a buffer, for example. Or, because on the Pi a server crash means an sclang crash, we may find that our program crashes much more often, so we want to leave notes to ourself, telling the program where it should start up again.</p><p>On the other hand, SD cards are not as robust as a normal disk drive. They have a limited number of writes before they die. (<b>Always make a copy of your SD card!</b>) The raspbian operating system does a lot of file writes already. Some Pi users have instructions on how to vastly reduce the number of writes. If you are concerned about the longevity of your SD card, the questions to ask yourself are about budget ('Can I afford the more expensive SD cards that will last longer?' 'How many spares can I keep on hand?') and the installation longevity ('Is this going to run for days or for weeks / months / years? Can I just give a small stack of duplicate SD cards to the organisation running it and will they be able to manage recognising the installation is borked and putting in a new card?'). For what it's worth, I have been using one SD card for more than two weeks of testing with no effort to reduce file writes and doing my own file writing. I have made an image of my SD card and plan to bring a couple of duplicates with me when I set up the installation.</p><h5>Crash Recovery</h5><p>Because everything on the installation eventually will crash, you need to keep in mind that a program writing a file will sometimes crash mid-write. Therefore, the program reading the files needs to check if the file exists before opening it, and then, once open, check if it has been corrupted. Note that since the system will sometimes reboot, the writer may have been just partway through writing the file when the system went down.</p><p>When my installation is running, I keep my files in <code>/tmp</code>. This is a special directory on Raspbian (and other unix systems, including Mac OS X) that holds files that are meant to be temporary. When the system reboots, /tmp is completely erased. Therefore, when my script starts, I copy files I will need to read and modify to /tmp, so that I know I'm starting with a clean slate after a reboot.</p><h3>Autostart</h3><p>I have only done autostarting with a system that boots to a desktop. If you do not, you will need to look into another way of starting. I would suggest picking one that is not tied to logging in. You should be able to open as many or as few ssh connections as you would like, without accidentally firing off many copies of your script.</p><p>For Pis that boot to a desktop, you will need to create a file called installation.desktop. Put in it:</p><pre><code>
[Desktop Entry]
Name=Installation
Exec=/home/pi/installation/installation.sh
Type=application
</code>
</pre><p>Change the name and the exec line to match your actual file names and paths. Save that file to <code>~/.config/autostart/</code>. This is a hidden directory, so if you can't find in your gui, save the file in your home directory and then open a terminal and type <code>mv installation.desktop ~/.config/autostart/</code> . When your computer boots, it will now automatically start your installation when the desktop opens.</p><h4>Stopping the installation</h4><p>If you just want to stop everything, shut down the computer! <code>shudo shutdown -h now</code> But if you want to stop the installation and keep the computer going, this is also possible! You might want to do this because you are updating files or testing. Remember that SD cards are pretty cheap, so if you just need a Raspbian system with SuperCollider on it, you should probably keep that on a separate SD card.</p><p>When you log in, the first thing you will want to kill is the bash script that is running everything. Then, you will want to kill sclang, the server and jackd and your helper apps. You can type:</p><pre><code>
killall installation.sh
killall sclang
killall scsynth
killall jackd
</code>
</pre><p>To get a list of everything running, use the ps command: <code>ps -u pi</code> . It will print out a list of everything running that belongs to the user pi (that's us!). The number on the left of the listing is the PID (Processed ID) and the name on the left is the name of the program. If you see your helper script has a PID of 27142, you can kill it directly: <code>kill 27142</code>. If you notice that your programs are resisting your effort to kill them, you can force them to die: <code>kill -9 27142</code>, where the number is what you see when you run ps.</p><h3>Debugging</h3><p>In our bash script above, we've got a lot of reboots. This is how the script will look when we deploy it, but not how it should be early in the testing process. We instead want to run the script ourselves, from the command line, so we can see what is being printed out in the way of error codes or from printlns in SuperCollider. Therefore, when first trying this, we would replace all of our '<code>sudo shutdown -r now</code>' lines with '<code>exit</code>'. We may need to reboot anyway when the program stops, but this will give a chance to try to read what went wrong. This can also tell us that, say, the server never wants to start, which may indicate that we have not slept for long enough after starting jack.</p><p>To launch a script form the command line, cd to the directory that its in and type: <code>./installation.sh</code> . The ./ at the beginning of the command just says that the script is local to the directory that we're in.</p><p>Once the script and program are fairly stable, though, we will want to just leave the installation running, to see if it gets stuck in a state where it stops without restarting or rebooting. When we're ready to do that, we will put the shutdown commands back in and that's when we have the script autostart.</p><p>When you've autostarted your program, it runs silently. How can you tell what's going on? It may be helpful to just know what's running at any given time. You can do that via the desktop by running the Task Manager. Or you can to do it from the command line by running <code>top -u pi</code>. This will keep us current on what is running on the system. Is your helper app still going? Is scsynth dying every 10 seconds, causing an endless loop of crashes? Is everything starting when it should and staying alive long enough? This also tells you what is using up the most CPU resources. Does your helper app climb up to 100% before the server crashes?</p><p>If you are getting weird crashes that you didn't get when developing the code on your own computer, then one possible problem is the pi version of your startup script. Make a copy of the script and change it so that it always runs as if you are on a Pi. Try it on your own computer (changing the paths as appropriate). Maybe the logic got slightly screwed up.</p><p>Maybe your helper script is too nice and the output isn't ready when sclang needs it? Because the Pi has such low power, your program will need to be able to deal with late data. Changing nice values may not be enough to solve this problem. You will need to make sure your SuperCollider program can cope with data arriving late.</p><p>Or maybe your helper script isn't nice enough. If it's always at the top in top, it might not be leaving enough space for your server to run. If the server can't get enough CPU, the audio will sound weird and fragmented and the server will crash. This leads to a lot of waiting for everything to restart itself! If you are tending to be using a high percentage of the CPU, scsynth needs to be getting its share of that.</p><p>Does your program start out ok, but then seem to always need to reboot in order to recover from a crash? Try making it sleep longer at the end of the loop. Sleeping for several extra seconds in between restarting jack, ssynth and sclang may seem like a long wait between running things, but it's a shorter wait than a reboot.</p><h3>the aesthetic of glitch</h3><p>You may want to create a long, lush drone that has a relatively simple synthdef, which just starts and runs without getting messages from sclang. That's not going to crash very often. You will have tons of uptime. Give it a try and see if the Pi will work for you.</p><p>Or you might want to start a ton of short, complex synths that rely on doing strange calculations, where the possibility of failure is inherent in the process. (Welcome to my world.) That will definitely crash. There will be long silences while the installation sorts itself out. Therefore, this needs to be a part of your aesthetic that you deal with using some sort of intentionality. You might want to consider having sudden stops and pauses happen when your piece is not crashed, so that a crash just seems like a longer pause. If your piece is using the desktop to do any kind of graphics, set a background image that works within the context of someone experiencing your piece. When the system reboots, people will see that background image, so it should be approached as a part of the installation.</p><p>Your audience needs to be prepared for pauses. Foreshadowing in the output is an important part of this, but my last bit of advice is to put something in the program notes, so a person approaching the installation knows it sometimes takes short breaks and may be willing to wait a few minutes if they happen to walk up as it is crashing in a way that will require a reboot.</p><h3>Conclusion</h3><p>This document has mostly spoken about the disadvantages of the Pi, sometimes at great length. However, if you are reading this while considering running an installation on the Pi, do not despair. The advantages of the Pi may still be greater than the disadvantages.</p><ul><li>It is still small and cheap, thus making it ideal for installations (and for shipping in the post). <br />
<li>It has a certain coolness factor, which may make venues more interested in your work. <br />
<li>An SD card is a stable platform. Once you get an installation working, if you want to run it again a year from now, you don't need to worry overly about system updates, etc. It should just still work.<br />
<li>You can do risky things. Again, if you do something really weird that breaks your system, you can just re-image the sd card. Be bold and audacious. <br />
</ul>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com1tag:blogger.com,1999:blog-10668379.post-50827398137194035372014-12-12T08:08:00.000-05:002014-12-12T08:08:09.369-05:00Last Week's Notes<p>Note: This is here temporarily for the benefit of some students. It will move to Moodle and disappear form here</p><code><br />
<pre>/*
SuperCollider is an Object Oriented Language that is designed for music and audio. It is a Music V type language. that means, like MAX MSP, the sound generation runs on a different thread than the control stuff. In MAX / MSP, you see this represented by differented coloured patch connections. In SuperCollider, audio runs on a server.
Because we don't have much time, I'm going to ask you take notes and then try stuff out later, not in class. I also will ask Pieman to put a tutorial up for you on Moodle.
Hopefully you all have SuperCollider installed. When you tried opening it, you saw the screen divided in two parts. One part was the post window, filled with strange text and the other part was just blank and called untitled. The untitled window is where you write your code. When you want to run your code, you select it with your mouse and hit ctrl-enter if you are in windows or linux, or apple-enter if you are on a mac. On some computers, you may need to use the apple or control key on the right wide of your keyboard. Try this out later with a simple program:
*/
4 + 4
/*
When you highlight 4 + 4 and run it, 8 will print out in your post window.
We're going to start out with working with sound design. Sound runs on the server. Therefore, we need to fist boot the server. There are a few ways to do this. If you look in the Language menu, one of the items is 'boot server'. Select that.
The text in the little status bar at the bottom should change and turn green. you will also see output in the post window.
Now that the server is booted, let's make some sound:
*/
(
SynthDef(\sine, {
Out.ar(0,
SinOsc.ar(440, 0, 0.2)
)
}).play
)
/*
When you want it to stop, hit ctrl-period or apple-period.
We are defining a SynthDef, sending it to the server and telling it to play. a synthDef is a description of how the server makes a sound.
First it has the name, which starts with a \, then comman curly bracket, then all of the UGens.
Out.ar is where the sound should come out. The channels start with 0, so this is on the left. Next is what should come out.
SinOsc is a sinwav oscillator. It's running at 440 Hz, it's phase is 0, and it's amplitude is 0.2.
Notice that these items have commas between them.
Then we close all of our open parens and curly brackets
Then a .play tells the whole thing to play.
We can organise this better using variables.
A variable is a container with a name. Like a box named sine. It can hold an object.
*/
(
SynthDef(\sine, {
var sine;
sine = SinOsc.ar(440, 0, 0.2);
Out.ar(0, sine);
}).play
)
/*
First we let SuperCollider know that we've got a variable named sine.
We end that with a semicolon, so it knows that statement is done.
Then we do an assignment. Don't read = as 'equals, read it as 'gets'.
sine gets SinOac.ar. We've got a box named sine. We've put a sine oscillator in the box, to keep track of it.
Then a semi colon, so it knows we're done with the assignment.
Then Our.ar, saying what channel to go out on. And we tell it, put out whatever's in sine. Take the contents of the box and send it to the left speaker.
Every line needs to be separated by semicolons. Later on, when you can't figure out why something isn't working, check the semi colons first. It's the most common mistake. I still forget them all the time.
These sines all last forever, so let's try an envelope:
*/
(
SynthDef(\sinenv, {
var sine, env;
sine = SinOsc.ar(440, 0, 0.2);
env = EnvGen.kr(Env.perc, doneAction:2);
Out.ar(0, sine * env);
}).play
)
/*
we have added an extra variable called env
We've put an EnvGen into it. env gets EnvGen.kr. An EnvGen is an envelope generator. First we tell it what envelope shape, then we do this doneAction:2 thing.
When we're telling out what to play, we tell it to multiple the sine box by the env box.
Let's do some ring modulation:
*/
(
SynthDef(\sinerm, {
var sine, ringmod, env;
sine = SinOsc.ar(440, 0, 0.2);
ringmod = SinOsc.ar(30) * sine;
env = EnvGen.kr(Env.perc, doneAction:2);
Out.ar(0, ringmod * env);
}).play
)
/*
We've added a new variable called ringmod.
Ring mod gets a new sinosc times the contents of the sine variable.
When SuperCollider is looking at your code and it sees an assignment - the equals sign - it does everything on the right hand side of the assingment and puts the result of everything into the variable on the left.
We've picked 30 Hz, because that's the frequency daleks use, but what if we want different frequencies?
We could keep changing the synthdef:
*/
(
SynthDef(\sinerm, {
var sine, ringmod, env;
sine = SinOsc.ar(470, 0, 0.2);
ringmod = SinOsc.ar(30) * sine;
env = EnvGen.kr(Env.perc, doneAction:2);
Out.ar(0, ringmod * env);
}).play
)
(
SynthDef(\sinerm, {
var sine, ringmod, env;
sine = SinOsc.ar(810, 0, 0.2);
ringmod = SinOsc.ar(30) * sine;
env = EnvGen.kr(Env.perc, doneAction:2);
Out.ar(0, ringmod * env);
}).play
)
(
SynthDef(\sinerm, {
var sine, ringmod, env;
sine = SinOsc.ar(752, 0, 0.2);
ringmod = SinOsc.ar(30) * sine;
env = EnvGen.kr(Env.perc, doneAction:2);
Out.ar(0, ringmod * env);
}).play
)
/*
Or, we could use a special kind of variable called an argument
*/
(
SynthDef(\sinermarg, { arg freq;
var sine, ringmod, env;
sine = SinOsc.ar(freq, 0, 0.2);
ringmod = SinOsc.ar(30) * sine;
env = EnvGen.kr(Env.perc, doneAction:2);
Out.ar(0, ringmod * env);
}).add
)
/*
We've declared the argument at the top. That uses the keyword arg. argument need to go before variables.
So first you have the SynthDef and the name of it and the culry bracked.
Then next is arguments, starting with the keyword arg.
then are the variables, starting with the keyword var.
Everything else is below that.
It does not make sound when we play this one, because we changed the .play at the end to .add.
Instead of playing this right away, we tell the server to remember it, so we can play it later.
*/
Synth(\sinermarg, [\freq, 440])
/*
there are a lot of ways we can play a SynthDef, and one of them is by via Synth.
The first argument to Synth is \sinermarg, which is the name of the synthdef. The next is this square bracket thing.
The first thing in the square brackets is \freq, this is the name of our argument, but starting with a slash.
Then is the value we want to give it.
*/
Synth(\sinermarg, [\freq, 860])
/*
What if we want to have more arguments?
*/
(
SynthDef(\sinermargs, { arg freq, rm, dur, amp;
var sine, ringmod, env;
sine = SinOsc.ar(freq, 0, amp);
ringmod = SinOsc.ar(rm) * sine;
env = EnvGen.kr(Env.sine(dur), doneAction:2);
Out.ar(0, ringmod * env);
}).add
)
Synth(\sinermargs, [\freq, 912, \rm, 123, \dur, 7, \amp, 0.3])
/*
For this morning, we're going to focus more on SynthDefs, so we'll get to do sequences of notes in the afternoon.
Let's try different waves, panned to centre
*/
(
SynthDef(\saw, { arg freq, dur, amp;
var saw, env, panner;
saw = Saw.ar(freq, amp);
env = EnvGen.kr(Env.sine(dur), doneAction:2);
panner = Pan2.ar(saw, 0,env);
Out.ar(0, panner);
}).add
)
Synth(\saw, [\freq, 550, \dur, 3, \amp, 0.2])
/*
Notice that saw and sign have different arguments in their list. the second thing in the list to sign is a 0 and the amplitude is third. But saw just goes directly from frequency to amplitude.
How would you know about how these are different (or even what the various oscillators are)? the answer is in the help browser!
Under the Help menu, there is a 'show help browser' option. You can click on search there to start searching. Or just browse around. Get to know the help browser. It is your friend. There are lots of examples.
Let's try some filtered noise:
*/
(
SynthDef(\subtractive, { arg freq, dur, amp;
var noise, filt, env, panner;
noise = WhiteNoise.ar;
filt = RLPF.ar(noise, freq);
env = EnvGen.kr(Env.sine(dur), doneAction:2);
panner = Pan2.ar(filt, 0,env * amp);
Out.ar(0, panner);
}).add
)
Synth(\subtractive, [\freq, 1200, \dur, 3, \amp, 0.2])
/*
WhiteNoise is just noise, so there's no need to give it additional information
RLPF is a Resonant Low Pass Filter
You may have noticed some of these are .ar and some are .kr.
ar is audio rate
kr is control rate
The envelope doesn't need to change values as often as a 440 Hz sine oscillator in order to sound good. The oscillator needs to go through it's entire wave form 440 times a second, whereas, the envelope needs much less precision.
*/
/*
This file is a SuperCollider file. The english text is in a comment. Programmers sometimes want to put human-language notes in their files. This makes the files more readable to humans, but the text is not meaningful to SuperCollider. They mark the text as not being code by putting comment markers around it. Every one of these block of text starts with a slash star and ends with a star slash.
*/
/* <-- this is the starts of a comment
this is the end of a comment ---> */
// <- this marks a comment that only lasts for one line (and thus does not need an end marker)
</pre></code>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com1tag:blogger.com,1999:blog-10668379.post-33218324100766085732014-12-12T07:46:00.002-05:002014-12-12T07:46:07.877-05:00Pbind Notes from this morning<p>Note: This is here temporarily for the benefit of some students. It will go up on Moodle and then be removed from here.</p><code><br />
<pre>/*
Now what we want is a way to play notes in sequence. Let's use an earlier synthdef:
*/
(
SynthDef(\sin, { arg freq = 440, dur = 1, amp= 0.5, pan=0;
var sine, env, panner;
sine = SinOsc.ar(freq, 0, amp);
env = EnvGen.kr(Env.perc(0.01, dur), doneAction:2);
panner = Pan2.ar(sine, pan, env);
Out.ar(0, panner);
}).add
)
(
Synth(\sin, [\freq, 440, \dur, 1, \amp, 0.3]);
Synth(\sin, [\freq, 550, \dur, 1, \amp, 0.3]);
Synth(\sin, [\freq, 660, \dur, 1, \amp, 0.3]);
)
/*
This plays all at once!
Fortunately, there are several ways to add timings. One of these is Pbind.
*/
Pbind.new.play
/*
As before, press cntl-. or apple-. to stop
Pbind makes a LOT of assumptions on your behalf, so you can run it with no arguments at all. Or you can specify as much as you want.
Let's tell it to use our synthdef:
*/
(
Pbind(
\instrument, \sin
).play
)
/*
Let's tell it to play louder
*/
(
Pbind(
\instrument, \sin,
\amp, 0.5
).play
)
// Change the freq and dur
(
Pbind(
\instrument, \sin,
\amp, 0.5,
\freq, 770,
\dur, 0.5
).play
)
/*
This is better, but let's make the notes change over time
*/
(
Pbind(
\instrument, \sin,
\amp, 0.5,
\freq, Pseq([440, 550, 660, 770, 880], 1),
\dur, 0.5
).play
)
/*
Pseq plays all the array contents in order, then repeats the number of times listed
*/
(
Pbind(
\instrument, \sin,
\amp, 0.5,
\freq, Pseq([440, 550, 660, 770, 880], 3),
\dur, 0.4
).play
)
/*
To repeat forever, use the keyword inf
*/
(
Pbind(
\instrument, \sin,
\amp, 0.5,
\freq, Pseq([440, 550, 660, 770, 880], inf),
\dur, 0.2
).play
)
/*
We can use Pseqs for ANY item in a Pbind
*/
(
Pbind(
\instrument, \sin,
\amp, 0.5,
\freq, Pseq([440, 550, 660, 770, 880], inf),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 2)
).play
)
/*
The first Pseq that ends, ends the entire Pbind
Instead of specifying frequencies let's switch to scale degrees
*/
(
Pbind(
\instrument, \sin,
\amp, 0.5,
\degree, Pseq([0, 2, 4, 6, 7], inf),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 2)
).play
)
/*
The Pbind does the maths for us to map the scale degrees to the frequency. This works because our synth uses the argument freq for frequency. the Pbind assumes this is what the frequency argument will be called and acts accordingly.
We can change to a different number of scale steps
*/
(
Pbind(
\instrument, \sin,
\amp, 0.5,
\stepsPerOctave, 10,
\degree, Pseq([0, 2, 4, 6, 7], inf),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 2)
).play
)
/*
We can change scales
*/
(
Pbind(
\instrument, \sin,
\amp, 0.5,
\scale, Scale.minor,
\degree, Pseq([0, 2, 4, 6, 7], inf),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 2)
).play
)
/*
Look up scales in the help browser for more
(incidentally, when you want to search, the search box at the top right searches only the currently displayed page. to search everything, click on the word 'search' on the top.
We can do maths with Pseqs
*/
(
Pbind(
\instrument, \sin,
\amp, 0.5,
\scale, Scale.minor,
\degree, Pseq([0, 2, 4, 6, 7], inf) + Pseq ([0, 0, 0, 0, 0, 5, 5, 5, 5], inf),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 10)
).play
)
/*
We can nest Pseqs
*/
(
Pbind(
\instrument, \sin,
\amp, 0.5,
\scale, Scale.minor,
\degree, Pseq([0, 2, 4, 6, 7], inf) +
Pseq ([
Pseq([0], 5),
Pseq([5], 4)
], inf),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 10)
).play
)
/*
They can also be multiplied, divided, etc.
We can play multiple notes at once:
*/
(
Pbind(
\instrument, \sin,
\amp, 0.3,
\scale, Scale.minor,
\degree, Pseq([[1, 3], [3, 5, 7], [2, 5], 7, [1,8]], inf),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 2)
).play
)
/*
If a pseq gets an array back for any value, it will make as many notes as are in the array, each with one of the values in the array.
So when it gets [3, 5, 7] for the degree, it makes one note with the 3rd, one with the 5th and one with the 7th.
We can not always use direct sequences
*/
(
Pbind(
\instrument, \sin,
\amp, 0.5,
\scale, Scale.minor,
\degree, Prand([0, 2, 4, 6, 7], 3),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 2)
).play
)
/*
Prand picks an item randomly from the array, the amount of times you tell it to. So rather than playing through everything 3 times, it picks 3 items
*/
(
Pbind(
\instrument, \sin,
\amp, 0.5,
\scale, Scale.minor,
\degree, Prand([0, 2, 4, 6, 7], inf),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 2)
).play
)
/*
Prands can do all the same maths as Pseqs and work in combination with them
*/
(
Pbind(
\instrument, \sin,
\amp, 0.5,
\scale, Scale.minor,
\degree, Prand([0, 2, 4, 6, 7], inf) + Pseq ([0, 0, 0, 0, 0, 5, 5, 5, 5], inf),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 10)
).play
)
(
Pbind(
\instrument, \sin,
\amp, 0.3,
\scale, Scale.minor,
\degree, Prand([0, 2, 4, 6, 7, [1, 3, 5]], inf) + Pseq ([0, 0, 0, 0, 0, 5, 5, 5, 5], inf),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 10)
).play
)
(
Pbind(
\instrument, \sin,
\amp, 0.3,
\scale, Scale.minor,
\degree, Prand([0, 2, 4, 6, 7, [1, 3, 5]], inf) + Pseq ([
Pseq([0], 5),
Pseq([5], 4),
Prand([0, 2, 5], 1)
], inf),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 10)
).play
)
/*
Pwhite varies randomly between a low and a high number
*/
(
Pbind(
\instrument, \sin,
\amp, 0.3,
\scale, Scale.minor,
\degree, Prand([0, 2, 4, 6, 7, [1, 3, 5]], inf) + Pseq ([
Pseq([0], 5),
Pseq([5], 4),
Prand([0, 2, 5], 1)
], inf),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 10),
\pan, Pwhite(-1, 1, inf)
).play
)
/*
The panning is hard left, hard right or center, because it's only picking whole number. If we want it to pick numbers between the whole numbers, we need to specify that
*/
(
Pbind(
\instrument, \sin,
\amp, 0.3,
\scale, Scale.minor,
\degree, Prand([0, 2, 4, 6, 7, [1, 3, 5]], inf) + Pseq ([
Pseq([0], 5),
Pseq([5], 4),
Prand([0, 2, 5], 1)
], inf),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 10),
\pan, Pwhite(-1.0, 1.0, inf)
).play
)
/*
The whole numbers are called intergers and the numbers with decimal points are called floating point or floats, which are terms you might see in the help files.
*/
/*
This behaviour is actually useful, if we want to pick scale degrees, we may not what to pick ones in between
*/
(
Pbind(
\instrument, \sin,
\amp, 0.5,
\scale, Scale.minor,
\degree, Pwhite(0, 8, 10),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 10),
\pan, Pwhite(-1.0, 1.0, inf)
).play
)
(
Pbind(
\instrument, \sin,
\amp, 0.5,
\scale, Scale.minor,
\degree, Pwhite(0.0, 8.0, 10),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 10),
\pan, Pwhite(-1.0, 1.0, inf)
).play
)
/*
What if we want moments of silence?
we use the symbol \rest for the freq or degree
*/
(
Pbind(
\instrument, \sin,
\amp, 0.3,
\scale, Scale.minor,
\degree, Pseq([0, 2, \rest], 3),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 10),
\pan, Pwhite(-1.0, 1.0, inf)
).play
)
(
Pbind(
\instrument, \sin,
\amp, 0.3,
\scale, Scale.minor,
\degree, Prand([1, 3, 5, 7, 8, [1, 3, 5], \rest], inf) + Pseq ([
Pseq([0], 5),
Pseq([5], 4),
Prand([0, 2, 5], 1)
], inf),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 10),
\pan, Pwhite(-1.0, 1.0, inf)
).play
)
/*
What if we want to do one thing and go on to another thing?
*/
(
Pseq([
Pbind(
\instrument, \sin,
\amp, 0.3,
\scale, Scale.minor,
\degree, Prand([1, 3, 5, 7, 8, [1, 3, 5], \rest], inf) + Pseq ([
Pseq([0], 5),
Pseq([5], 4),
Prand([0, 2, 5], 1)
], inf),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 2),
\pan, Pwhite(-1.0, 1.0, inf)
),
Pbind(
\instrument, \sin,
\amp, 0.3,
\stepsPerOctave, 10,
\degree, Pwhite(1, 10, 10),
\dur, Prand([0.4, 0.6, 0.8], inf)
)
]).play
)
(
Pseq([
Pbind(
\instrument, \sin,
\amp, 0.3,
\scale, Scale.minor,
\degree, Pseq([0, 2, \rest], 3),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 10),
\pan, Pwhite(-1.0, 1.0, inf)
),
Pbind(
\instrument, \sin,
\amp, 0.3,
\stepsPerOctave, 10,
\degree, Pwhite(1, 10, 10),
\dur, Prand([0.4, 0.6, 0.8], inf)
)
]).play
/*
What if we don't just want chords, but want two streams going at once?
*/
(
SynthDef(\crapSnare, { arg amp, pan;
var noise, env, panner;
noise = WhiteNoise.ar;
env = EnvGen.kr(Env.perc, doneAction:2);
panner = Pan2.ar(noise, pan, env);
Out.ar(0, panner * amp)
}).add
)
(
Ppar([
Pbind(
\instrument, \sin,
\amp, 0.3,
\scale, Scale.minor,
\degree, Prand([1, 3, 5, 7, 8, [1, 3, 5], \rest], inf) + Pseq ([
Pseq([0], 5),
Pseq([5], 4),
Prand([0, 2, 5], 1)
], inf),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 10),
\pan, Pwhite(-1.0, 1.0, inf)
),
Pbind(
\instrument, \crapSnare,
\amp, 0.2,
\dur, 0.8
)
]).play
)
// note the snare never stops!
// or moving the snare to the offbeat:
(
Ppar([
Pbind(
\instrument, \sin,
\amp, 0.3,
\scale, Scale.minor,
\degree, Prand([1, 3, 5, 7, 8, [1, 3, 5], \rest], inf) + Pseq ([
Pseq([0], 5),
Pseq([5], 4),
Prand([0, 2, 5], 1)
], inf),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 10),
\pan, Pwhite(-1.0, 1.0, inf)
),
Pbind(
\instrument, \crapSnare,
\amp, 0.2,
\dur, Pseq([0.4, Pseq([0.8], inf)], 1)
)
]).play
)
/*
to get rid of the first beat, we need to give it a rest for the freq.
It does not matter that the synthDef doesn't take freq as an argument. This is just for the safe of the pbind
*/
(
Ppar([
Pbind(
\instrument, \sin,
\amp, 0.3,
\scale, Scale.minor,
\degree, Prand([1, 3, 5, 7, 8, [1, 3, 5], \rest], inf) + Pseq ([
Pseq([0], 5),
Pseq([5], 4),
Prand([0, 2, 5], 1)
], inf),
\dur, Pseq([0.2, 0.2, 0.4, 0.2, 0.6], 10),
\pan, Pwhite(-1.0, 1.0, inf)
),
Pbind(
\instrument, \crapSnare,
\amp, 0.2,
\dur, Pseq([0.4, Pseq([0.8], inf)], 1),
\freq, Pseq([\rest, Pseq([440], inf)], 1),
)
]).play
)
/*
Ppars can also be nested in Pseqs.
The helpfiles for streams patterns and events go into loads of detail about how to use p-things
When you are making your own pbinds, watch out for forgetting commas in the middle of them, or dangling commas at the end. commas should go between items.
*/
/* Finally, we might have a synth that lasts for a really long time, that we want to change, but not end
*/
(
SynthDef(\sinerm, {arg freq, amp;
var sine, ringmod, env;
sine = SinOsc.ar(freq, 0, 0.2);
ringmod = SinOsc.ar(30) * sine;
Out.ar(0, ringmod * amp);
}).play
)
(
Pmono(\sinerm,
\degree, Pwhite(0, 12, inf),
\amp, 0.5,
//\stepsPerOctave, 10,
\db, -3
).play
)
// We can change the synthdef a bit to add some lag
(
SynthDef(\sinermlag, {arg freq, amp;
var sine, ringmod, env, lag;
lag = Lag.kr(freq);
sine = SinOsc.ar(lag, 0, 0.2);
ringmod = SinOsc.ar(30) * sine;
Out.ar(0, ringmod * amp);
}).play
)
(
Pmono(\sinermlag,
\degree, Pwhite(0, 10, inf),
\amp, 0.5,
\stepsPerOctave, 10,
\db, -3 // Pmono and Pbind will translate db to amp for us
).play
)
/*
Algorave: uses algorythms to generate dance music
Can be live-coded, but need not be
Examples:
Microrex https://soundcloud.com/micorex
Yee-king http://open.spotify.com/track/1UTiLOe4LwarRDWR5pmjZg
Norah Lorway http://earthrid.bandcamp.com/album/ive-had-dreams-like-this
*/
</pre></code>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com0tag:blogger.com,1999:blog-10668379.post-86581079364436954362014-12-12T07:41:00.000-05:002014-12-12T07:41:40.420-05:00Some Notes for Students Today<div dir="ltr" style="text-align: left;" trbidi="on"><p>Note: This is literally for some students I have today. It will appear on Moodle some time soon and then disappear from this space.</p><code><br />
<pre>/*
Extra Things!
Q: How do you make a Pmono stop?
A: A Pmono stops when it runs out of values, to send, just like a Pbind. However, unless we tell a synth to stop, it will keep going forever.
Q: How do you tell a synth to stop?
A: Envelopes! We've seen this already with fixed duration envelopes. But if we don't know from the start how long we want the synth to go for, when need to use a different kind of envelope.
For example, and ASR.
ASR stands for 'attack, sustain, release and is a very common envelope in electronic music. It uses a 'gate' to know when to start and stop. When the gate is 1, the envelope starts doing the attack, then it sustains indefinitely. As soon as the gate changes to 0, it immeditately stops whaever its doing to do the release portion.
Ex:
*/
(
SynthDef(\blipGate, {|freq, amp, gate=1, pan| // the vertical bars are equvalent to using the keyword arg
var blip, panner, env;
blip = Blip.ar(freq, 10, 0.2);
env = EnvGen.kr(Env.asr, gate, doneAction:2); // look at the helpfile for Env for more
panner = Pan2.ar(blip, pan, env);
Out.ar(0, panner * amp);
}).add
)
(
Pmono(
\blipGate,
\pan, Pwhite(0.0, 1.0, 5),
\degree, Pwhite(1, 4, 5)
).play
)
// gates also work with Pbinds
(
Pbind(
\instrument, \blipGate,
\pan, Pwhite(0.0, 1.0, 5),
\degree, Pwhite(1, 4, 5)
).play
)
/*
Q: How can I make frequency changes less abrupt?
A: Add in some lag:
*/
(
SynthDef(\blipLag, {|freq, amp, gate=1, pan| // the vertical bars are equvalent to using the keyword arg
var lag, blip, panner, env;
lag = Lag.kr(freq);
blip = Blip.ar(lag, 10, 0.2);
env = EnvGen.kr(Env.asr, gate, doneAction:2); // look at the helpfile for Env for more
panner = Pan2.ar(blip, pan, env);
Out.ar(0, panner * amp);
}).add
)
(
Pmono(
\blipLag,
\pan, Pwhite(0.0, 1.0, 5),
\degree, Pwhite(1, 4, 5)
).play
)
/*
Q: If you're live coding and want to change a pbind without stopping it, can you do that?
A: Yes, with Pdef
*/
(
Pdef(\blips,
Pbind(
\instrument, \blipGate,
\pan, Pwhite(0.0, 1.0, inf),
\degree, Pwhite(1, 4, inf),
\dur, 0.4
)
).play
)
// just put a Pdef around the pbind
// now, let's change without stopping
(
Pdef(\blips,
Pbind(
\instrument, \blipGate,
\pan, Pwhite(0.0, 1.0, inf),
\degree, Pwhite(1, 4, inf),
\dur, Prand([0.4, 0.2, 0.2, 0.8], inf)
)
).play
)
// another change
(
Pdef(\blips,
Pbind(
\instrument, \blipGate,
\pan, Pwhite(0.0, 1.0, inf),
\degree, Pwhite(1, 4, inf) * Pwhite(1, 2),
\dur, Prand([0.4, 0.2, 0.2, 0.8], inf)
)
).play
)
Pdef(\blips).fadeTime = 5; // tell it to fade changes in and out over 5 seconds
Pdef(\blips).stop; // tell it to stop (but don't stop anything else, including other Pdefs)
/*
Q: what are some good oscillators?
A:
SinOsc
Blip
Formant
Pulse
Saw
Klank
// look at the help files for those
Ok, now I want you folks to get to work making some sounds and patterns. I'll come around to answer questions, or you can pair up if you want.
*/
</pre></code><br />
</div>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com0tag:blogger.com,1999:blog-10668379.post-71236641007444099752014-05-22T11:03:00.000-04:002014-05-27T16:52:44.810-04:00How to keep an installation running<p>Writing a program that can make it through the length of a single 20 minute performance can sometimes be challenging, but installation code needs to run for a full day or sometimes weeks and keep going. The first step, of course, is to make your code as bug-free as possible. However, even in this case, your code will eventually crash, though no wrong doing of your own. Therefore, the thing to do is to recover gracefully.</p><p>The latest versions of SuperCollider are actually three programs running at once - the IDE; sclang, the language; and scserver, the audio server. Any one of these things can crash.</p><h3>SkipJack</h3><p>SkipJack is an object that is like a Task, except that it survives cmd-period. It takes several arguments, the first of which is a function and the second of which is a number indication the wait time in between executions of the function.</p><code>SkipJack({"SkipJack".postln}, 2)</code><br />
<p>This code would print out SkipJack once every two seconds. The advantage of using SkipJack in this case is not that it will keep going after a comand-periiod, but rather that it's on a different thread than the rest of your program. If your main execution loop gets stuck some place and effectively dies, SkipJack will likely carry on. Therefore, we can use SkipJack to check on your main loop and try to revive it.</p><h3>Sclang</h3><p>How can we tell your main thread is still running without also stopping if it stops? One way to check is by looking at a shared variable. Let's have a number. Every time we go through the loop, we can set it to 3. Meanwhile, SkipJack could be running with a duration roughly equivalent to how long it should take to get through our loop. It could subtract one from our number. If our main execution loop stops, that number will count down towards zero and then go negative.</p><code><br />
var alive, click, dur, task;<br />
<br />
dur = 2;<br />
click = { alive = 3 };<br />
<br />
task = Task({<br />
inf.do({<br />
<br />
"still allive".postln;<br />
click.value;<br />
dur.wait;<br />
})<br />
}).play;<br />
<br />
SkipJack({<br />
"are we alive?".postln;<br />
(alive <=0).if({<br />
task.resume;<br />
task.play;<br />
"play!".postln;<br />
(alive <= -2).if({<br />
1.exit;<br />
})<br />
});<br />
alive = alive -1;<br />
}, dur);<br />
</code><br />
<p>If alive gets to zero, first we try to get the task running again. This sometimes works. If it fails, however, we call 1.exit, which causes all of sclang to exit. If we can't recover inside sclang, we can recover outside it.</p><h3>The Server</h3><p>We'll need a separate loop to check on the server.</p><code><br />
SkipJack({<br />
Server.default.boot(onFailure:{});<br />
Server.default.doWhenBooted({}, onFailure:{1.exit});<br />
<br />
}, dur);<br />
</code><br />
<p>This may look odd because it changes the 'onFailure' argument, but the effect of it is that if the server is not already booted, it will take a moment and may struggle to boot. If it fails, all of SuperCollider exits.</p><h3>Keeping a Synth Alive</h3><p>If your loop is firing off new Synths, you don't need to worry about whether each individual synth keeps going, but if you're just changing parameters on an individual synth that keeps running, you also need to watch out for it perishing. there are a few ways to do this. Maybe you want to check if it has gone silent?</p><code><br />
(<br />
var syn, lastrms, max_silence;<br />
<br />
SynthDef(\stereoListenForSilence, {|in=0, out=0|<br />
var input;<br />
input = In.ar(in, Server.default.options.numOutputBusChannels);<br />
SendPeakRMS.kr(input, 1, 3, '/loudnessMonitoring'); // send the RMS once per second<br />
ReplaceOut.ar(0, LeakDC.ar(input).tanh); // Optional line to get rid of offset and peaking<br />
}).add;<br />
<br />
/* ... */<br />
<br />
<br />
Synth(\stereoListenForSilence, nil, RootNode(s), \addToTail);<br />
<br />
max_silence = 10; // 10 seconds<br />
<br />
<br />
lastrms=Array.fill(max_silence, {1});<br />
<br />
osc_listener = OSCFunc({ |msg|<br />
var rms;<br />
rms = msg[4].asFloat.max(msg[6].asFloat);<br />
lastrms.removeAt(0);<br />
lastrms.add(rms);<br />
(lastrms.sum <= 0.0001).if ({<br />
"too quiet".postln;<br />
// retsart your synths<br />
s.freeAll;<br />
Synth(\myAmazingSynthDef);<br />
Synth(\stereoListenForSilence, nil, RootNode(s), \addToTail);<br />
});<br />
}, '/loudnessMonitoring');<br />
</code><br />
<br />
<p>You can put a monitoring Synthdef on the server's root node and use SendPeakRMS to send OSC messages with the overall amplitude of all running synthdefs. Then, set up an OSCFunc to check if the peak amplitude has been near zero for too long. If it has, free everything and put up new synths. This will not tell you if your server freezes or if your monitoring synth stops sending OSC messages.</p><p>Or if you just want to check if an individual Synth is still running, you can use OSCFuncs and SkipJack together.</p><code><br />
(<br />
<br />
var syn_alive, dur;<br />
<br />
dur =1;<br />
syn_alive = 3;<br />
<br />
SynthDef(\myAmazingSynthDef, {<br />
<br />
var sin, trig;<br />
SendTrig.kr(Impulse.kr(dur.reciprocal));<br />
sin = SinOsc.ar;<br />
Out.ar(0, sin);<br />
<br />
}).add;<br />
<br />
<br />
/* ... */<br />
<br />
Synth(\myAmazingSynthDef);<br />
<br />
OSCFunc({ arg msg, time;<br />
syn_alive = 3;<br />
},'/tr', s.addr);<br />
<br />
<br />
SkipJack({<br />
(syn_alive <=0).if({<br />
<br />
s.freeAll;<br />
Synth(\myAmazingSynthDef);<br />
<br />
(syn_alive <= -2).if({<br />
1.exit;<br />
})<br />
});<br />
syn_alive = syn_alive -1;<br />
}, dur);<br />
<br />
<br />
SkipJack({<br />
Server.default.boot(onFailure:{});<br />
Server.default.doWhenBooted({}, onFailure:{1.exit});<br />
<br />
}, dur);<br />
)<br />
</code><br />
<p>Try quitting the Server via the gui and everything gets back to where it was in under 3 seconds.</p><h3>No IDE</h3><p>Previously in this document, we've intentionally made sclang crash, which, if you're running the IDE, is no fun. However, we will not be running sclang through the IDE. Instead, we'll run it from a BASH script. On your computer (if you have a mac or unix), when you open a terminal, what's running in it is a Bash shell. You can write scripts for this shell, which you edit in a plain text editor.</p><code><br />
#!/bin/bash<br />
<br />
<br />
while true<br />
do<br />
<br />
/path/to/sclang installation.scd<br />
<br />
sleep 1<br />
<br />
killall scsynth<br />
<br />
sleep 1<br />
<br />
done<br />
</code><br />
<br />
<p>Ok, so first things first, open a terminal and type:</p><code>which bash</code><br />
<p>It may be /bin/bash or /usr/bin/bash. It's what you want in the first line of the bash script. So if you get back /usr/bin/bash, change the first line to #!/usr/bin/bash.</p><p>To find the path to sclang, you can try typing 'which sclang', but if you're on a mac, this is not going to work. Instead, you will need to find the SuperCollider application on you hard drive. Right click on it to examine package contents. If you poke around in there in folders called things like Resources or MacOs, you will eventually find sclang. Drag that file to your SuperCollider IDE to find out the path for it. Put that path into your bash script in the place of '/path/to/sclang'.</p><p>Save the script as installation.sh and save your supercollider file as installation.scd. Put them together in the same folder or directory. In your terminal window, cd to that directory and type:</p><code>chmod +x installation.sh</code><br />
<p>Or, alternately, if you'd prefer to use a GUI, get information about the installation.sh file and click a checkbox to make it executable.</p><p>What this script does is loop forever. It runs your program. When your program exists, it kills whatever server might still be running and then restarts your program. If your program crashes out entirely, this script will restart it.</p><h3>Helper Apps</h3><p>If your installation relies on a helper application, like let's say you're using PD to manage HID communications, you'll want that in your loop also, but as both applications are running at the same time, you'll need to run the helper application in the background, but keep track of the PID so you can kill it when your program crashes.</p><code><br />
#!/bin/bash<br />
<br />
<br />
while true<br />
do<br />
<br />
/path/to/pd hid_helper.pd &<br />
pid=$!<br />
/path/to/sclang installation.scd<br />
<br />
sleep 1<br />
<br />
killall scsynth<br />
kill $pid<br />
<br />
sleep 1<br />
<br />
done<br />
</code><br />
<p>Make sure your hid_helper is in the same folder as as your other files. Find the path to pd in the same way you got the path to sclang. The & makes it run in the background and the next line tracks the PID, so you can kill it later.</p><p>Obviously, you'll also want to keep track of your helper application, which you can do via OSC in the same way you keep track of your synthdefs. If your helper application quits, you'll need to do a 1.exit to force the bash script to restart everything.</p><h3>Making it all go</h3><p>This is an installation, so if you're using your own laptop, don't run it as yourself. Make a new user account and don't give that user administrative rights. Make all your files READABLE by that user (or everyone on the system), but don't give that user write access. Set the system so that when it boots up, it automatically logs in as that user.</p><p>Log in to the system as the new user. Go to the settings and say you want to autostart an application on login. The application you want to autostart is installation.sh</p><p>Try booting your computer. Does it start your installation? Once you've got that sorted out, leave it running in your living room for days and days until you think you're losing your mind. Every so often, use the process manager to kill the server or the helper application or wiggle a wire or otherwise create a bit of problems and see if your installation survives.</p>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com2tag:blogger.com,1999:blog-10668379.post-89893298766471827392010-10-13T16:03:00.002-04:002010-10-13T17:14:47.572-04:00Getting Started with BBCut2<h3>Installing</h3>
<p>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 <a href="http://www.cogs.susx.ac.uk/users/nc81/bbcut2.html">http://www.cogs.susx.ac.uk/users/nc81/bbcut2.html</a>. Then unzip it. Inside, you will find several directories.</p>
<ol>
<li>Move the "bbcut2 classes" directory to <span class="s4" style="font: normal normal normal 12px/normal Helvetica; ">~/Library/Application\ Support/SuperCollider/Extensions</span> . That tilda represents your home directory, so if your user name is nicole, you would put the file in <span class="s4" style="font: normal normal normal 12px/normal Helvetica; ">/Users/nicole/Library/Application\ Support/SuperCollider/Extensions</span> . If the Extensions directory does not exist on your system, then create it.</li>
<li>Put the "bbcut2 help" directory inside the classes directory that you just moved.</li>
<li>Put the "bbcut2 ugens" directory in<span class="s4" style="font: normal normal normal 12px/normal Helvetica; "> ~/Library/Application\ Support/SuperCollider/Extensions/sc3-plugins</span> . If this directory does not exist, then create it.</li>
<li>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 <span class="s4" style="font: normal normal normal 12px/normal Helvetica; ">/Applications/SuperCollider/sounds</span></li>
</ol>
<p>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.</p>
<h3>The Clock</h3>
<p>BBCut relies on a clock. When I'm coding, I usually base the clock off the default clock:</p>
<pre>
TempoClock.default.tempo_(180/60);
clock = ExternalClock(TempoClock.default);
clock.play;
</pre>
<p>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)</p>
<p>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: <span class="s4" style="font: normal normal normal 12px/normal Helvetica; ">clock = ExternalClock(TempoClock(182/60));</span></p>
<p>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.</p>
<h3>Working with Buffers</h3>
<p>There is a special sort of <a href="http://sc3howto.blogspot.com/2010/10/more-buffers.html">buffer</a> used by BBCut, called a <b>BBCutBuffer</b>. 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:</p>
<pre>
sf= BBCutBuffer("sounds/break",8);
</pre>
<p>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.</p>
<pre>
sf= BBCutBuffer("sounds/break",8);
Routine.run({
s.sync; // this tells the task to wait
// below here, we know all out Buffers are loaded
. . .
})
</pre>
<p>Now we can tell BBCut that we want to cut up a buffer and get it to start doing that.</p>
<pre>
cut = BBCut2(CutBuf3(sf)).play(clock);
</pre>
<p>BBCut2 is the class that runs everything, so we make a new one of these. Inside, we pass a <b>CutBuf</b>, which is a class that handles Buffer cutting. We tell the BBCut2 object to play, using the clock. This starts something going.</p>
<p>Cutting is much more interesting if it can jump around in the buffer a bit:</p>
<pre>
cut = BBCut2(CutBuf3(sf, 0.4)).play(clock);
</pre>
<p>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.</p>
<h3>Cut Procedures</h3>
<p>We can tell BBCut to use one of several <b>cut procedures</b>. The original one is called BBCutProc11.</p>
<pre>
cut = BBCut2(CutBuf3(sf, 0.4), BBCutProc11.new).play(clock);
</pre>
<p>It can take several arguments, which are: sdiv, barlength, phrasebars, numrepeats, stutterchance,
stutterspeed, stutterarea</p>
<ul>
<li>sdiv - is subdivision. 8 subdivsions gives quaver (eighthnote) resolution.</li>
<li>barlength - is normally set to 4 for 4/4 bars. If you give it 3, you get 3/4</li>
<li>phrasebars - the length of the current phrase is barlength * phrasebars</li>
<li>numrepeats - Total number of repeats for normal cuts. So 2 corresponds to a
particular size cut at one offset plus one exact repetition.</li>
<li>stutterchance - the tail of a phrase has this chance of becoming a repeating
one unit cell stutter (0.0 to 1.0)</li>
</ul>
<p>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:</p>
<pre>
cut = BBCut2(CutBuf3(sf, 0.4), BBCutProc11(8, 4, 2, 2, 0.2).play(clock)
</pre>
<p>We can tell the cutter to stop playing, or free it</p>
<pre>
cut.stop;
cut.free;
</pre>
<p>Putting all of what we have so far together, we get:</p>
<pre>
(
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;
})
)
</pre>
<p>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 <span class="s4" style="font: normal normal normal 12px/normal Helvetica; ">~/Library/Application\ Support/SuperCollider/Extensions/bbcut2\ classes/bbcut2\ help/BBCut2Wiki.help.rtf</span> or by selecting the text BBCut2Wiki and typing apple-d )</p>
<h3>Polyphony</h3>
<p>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.</p>
<pre>
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);
</pre>
<p>You can even mix and match sound files:</p>
<pre>
(
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;
})
)
</pre>
<p>If you want to also sync up a Pbind, you can use BBcut's clock via the playExt method:</p>
<pre>
Pbind.new(/* . . . */ ).playExt(clock);
</pre>
<p>Or, if you want to play an Event, you can use the tempo clock associated with the external clock</p>
<pre>
Event.new.play(clock.tempoclock);
</pre>
<h3>Groups and FX</h3>
<p>If we want to add fx to the chain, and take them back out, we can use a thing called a <b>CutGroup</b>:</p>
<pre>
// 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
group.add(CutMod1.new);
</pre>
<p>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:</p>
<pre>
(
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; //default CutMixer was added
g.add(CutComb1.new);
g.cutsynths.postln;
g.add(CutBRF1.new);
g.cutsynths.postln;
g.removeAt(2); //remove comb
g.cutsynths.postln;
</pre>
<p>Note that the fx that you add on start with index 2.</p>
<p>And also notice that you may get some errors in the post window when you remove fx: <span class="s4" style="font: normal normal normal 12px/normal Helvetica; ">FAILURE /n_set Node not found</span>. These are not usually a problem.</p>
<h3>Tying it all Together</h3>
<p>Here's an example using everything covered so far:</p>
<pre>
(
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;
})
)
</pre>
<h4>Summary</h4>
<ul>
<li>You must download BBCut2 from a website and install it by moving folders around.</li>
<li>The main BBCut helpfile is BBCut2Wiki</li>
<li>BBCut uses it's own clock, called ExternalClock, which relies on TempoClocks. </li>
<li>You must remember to start the clock</li>
<li>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.</li>
<li>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 <span class="s4" style="font: normal normal normal 12px/normal Helvetica; ">BBcut2(CutBuf1(sf), BBCutProc11.new).play(clock)</span></li>
<li>The cut procedures all have good help files.</li>
<li>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.</li>
<li>It is possible to add FX or remove FX from your chain by using CutGroup. </li>
</ul>
<h4>Problems</h4>
<ol>
<li>Get some of your own drum loops or rhythmic samples and try this out. You can find many loops at <a href="http://www.freesound.org/">http://www.freesound.org/</a>. Also, try some files with sustained tones.</li>
<li>Experiment with the arguments to BBCutProc11. Try your files with several different values.</li>
<li>Try out the different cut procedures. Look at their help files to find their arguments.</li>
<li>The FX are not as well documented, but they're located in <span class="s4" style="font: normal normal normal 12px/normal Helvetica; ">~/Library/Application\ Support/SuperCollider/Extensions/bbcut2\ classes/cutsynths/fx</span> . Try several of them out.</li>
</ol>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com5tag:blogger.com,1999:blog-10668379.post-58620841191759624842010-10-13T12:47:00.005-04:002010-10-13T13:54:40.154-04:00More Buffers<h3>Waiting</h3>
<p><a href="http://sc3howto.blogspot.com/2010/10/working-with-buffers.html">Last time</a>, 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.</p>
<p>If we use a Task (or a Routine), we can tell it to pause until the server has caught up.</p>
<pre>
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)
}).add;
buf = Buffer.read(s, "sounds/a11wlk01.wav");
Task.new({
s.sync; // wait for the server
Synth(\playBufMono, [\out, 0, \bufnum, buf.bufnum, \rate, 1])
}).play
)
</pre>
<p>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.</p>
<p>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:</p>
<pre>
s.boot;
(
var buf, bufloaded;
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)
}).add;
bufloaded = false;
buf = Buffer.read(s, "sounds/a11wlk01.wav",
action: { bufloaded = nil});
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
)
</pre>
<p>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.</p>
<p>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.</p>
<p>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:</p>
<pre>
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)
}).add;
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)
}).add;
buf1 = Buffer.read(s, "sounds/a11wlk01.wav");
Task.new({
s.sync; // wait for buf1
syn = Synth(\playBuf1, [\out, 0, \bufnum, buf1.bufnum,
\rate, 1, \loop, 1]); // play buf1
pink = Buffer.read(s, "sounds/SinedPink.aiff",
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
)
</pre>
<p>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.</p>
<p>If we wanted to, we could use the action to set a flag or do any number of other things.</p>
<h3>Recording</h3>
<p>We don't need to just play Buffers, we can also record to them. Let's start by allocating a new Buffer:</p>
<pre>
b = Buffer.alloc(s, s.sampleRate * 3, 1)
</pre>
<p>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.</p>
<p>Now, let's make a synth to record into it:</p>
<pre>
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);
}).add;
</pre>
<p>AudioIn.ar reads from our microphone or line in. Channels start at 1, for this UGen.</p>
<p>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.</p>
<p>We can mix this with a stuttering playback from earlier:</p>
<pre>
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)
}).add;
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);
}).add;
buf = Buffer.alloc(s, s.sampleRate * 3, 1);
Task({
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
)
</pre>
<h4>Summary</h4>
<ul>
<li>Buffers load asynchronously and we can't count on them to be ready unless we wait for them.</li>
<li>One way to wait is to call s.ync inside a Task or a Routine.</li>
<li>We can start playing back a Buffer from any sample with the startFrame argument.</li>
<li>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.</li>
<li>We can allocate empty Buffers on the server with Buffer.alloc.</li>
<li>AudioIn.ar starts with channel 1, even though most other input busses start at 0.</li>
<li>RecordBuf.ar records to a Buffer.</li>
</ul>
<h4>Problems</h4>
<ol>
<li>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.</li>
<li>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.</li>
<li>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.</li>
</ol>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com1tag:blogger.com,1999:blog-10668379.post-62163564257906478822010-10-03T11:58:00.005-04:002010-10-13T10:57:14.865-04:00Working with Buffers<p>Let's say you want to open a short audio file and play it back. You can do this with a <b>Buffer</b>.</p>
<pre>
s.boot;
b = Buffer.read(s, "sounds/a11wlk01.wav");
</pre>
<p>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.</p>
<p>The first argument, is therefore the server that will hold the buffer. The second is the path to the buffer on your computer.</p>
<p>Because the Buffer lives with the server, the command to read it is <b>asynchronous</b>. 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.</p>
<h3>PlayBuf</h3>
<p>To play the Buffer, you can use the UGen PlayBuf:</p>
<pre>
(
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]);
)
</pre>
<p>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.</p>
<p>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:</p>
<pre>
(
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]);
)
</pre>
<p>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.</p>
<p>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:</p>
<pre>
(
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)
}).add;
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)
}).add;
)
</pre>
<p>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.</p>
<p>To figure out which SynthDef to use, you can send the message numChannels to a buffer object:</p>
<pre>
(
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])
})
});
)
</pre>
<p>The second argument to PlayBuf is the bufnum. This tells it which Buffer to play.</p>
<p>The third argument is the rate. As mentioned above, it's a good idea to scale this rate with BufRateScale.kr</p>
<p>Buffers, like envelopes, can have a doneAction. 2 means to deallocate the synth from the server when the Buffer stops playing.</p>
<p>If you want to loop your buffer, that's also a possible argument:</p>
<pre>
(
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]);
)
</pre>
<p>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.</p>
<p>You can trigger a PlayBuf to jump back to the start:</p>
<pre>
(
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]);
)
</pre>
<p>Dust.ar returns impulses at random intervals. It's argument is the average number of impulses per second.</p>
<p>You can also tell the PlayBuf to start someplace else than the first sample:</p>
<pre>
(
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]);
)
</pre>
<p>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.</p>
<h3>Dialogs</h3>
<p>If you don't want to have to pick an audio file ahead of time, you can use Buffer.loadDialog:</p>
<pre>
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)
}).add;
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)
}).add;
b = Buffer.loadDialog(s);
)
(
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])
})
});
)
</pre>
<p>Note that you cannot load a compressed audio format like mp3 or ogg directly into a Buffer.</p>
<p>More on Buffers to come! </p>
<h4>Summary</h4>
<ul>
<li>Buffers live on the server</li>
<li>Every Buffer has a unique bufnum</li>
<li>You can change the playback rate of a Buffer. This should be scaled with BufRateScale</li>
<li>SynthDefs must be sent to the server already knowing how many channels PlayBuf.ar will play.</li>
<li>PlayBuf.ar will optionally take a doneAction</li>
<li>You can loop a Buffer, stuter it and tell it where to start</li>
<li>You can open a Buffer with a Dialog box</li>
<li>You cannot read an mp3 or ogg directly into a Buffer</li>
</ul>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com0tag:blogger.com,1999:blog-10668379.post-29216207805664971742010-08-03T13:13:00.008-04:002010-10-23T14:32:20.305-04:00Event<p>The most important subclass of Dictionary is <b>Event</b>:</p>
<pre>
(
var evt;
evt = Event.new;
evt.play;
)
</pre>
<p>Much like Arrays can be declared just by square brackets, Events can be declared just with parenthesees:</p>
<pre>
( ).play;
</pre>
<p>The sonic results of that line of code might sound familiar to you:</p>
<pre>
Pbind.new.play
</pre>
<p>This is not a coincidence! Patterns create Events and play them sequentially. Compare:</p>
<pre>
Pbind(\freq, 660, \pan, -1).play
</pre>
<p>and</p>
<pre>
(freq: 660, pan: -1).play
</pre>
<p>Note that the syntax for the Event is <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">(key: value, key2: value2)</span> . You can have as many <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">key: value</span> pairs as you want. In the example above, <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">freq</span> and <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">pan</span> are both symbols, both in the Pbind and the event.</p>
<p>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.</p>
<p>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."</p>
<p>In your Pbind, you can get access to the current event:</p>
<pre>
(
Pbind(
\freq, Pseq([550], 1),
\event, Pfunc({ |evt|
evt[\freq].postln;
})
).play
)
</pre>
<p>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, <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">\event</span>, that doesn't have meaning to the Synth, nor to the Event. This is allowed. For example:</p>
<pre>
(
Pbind(
\freq, Pseq([550], 1),
\foo, \bar
).play
)
</pre>
<p>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:</p>
<pre>
(
Pbind(
\event, Pfunc({ |evt|
"Pan before: %".format(evt[\pan]).postln;
}),
\pan, Pseq([-1], 1),
\event2, Pfunc({ |evt|
"Pan after: %".format(evt[\pan]).postln;
})
).play
)</pre>
<p>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.</p>
<p>Let's make the duration depend on the frequency:</p>
<pre>
(
Pbind(
\freq, Prand([440, 550, 660, 770], 10),
\dur, Pfunc({ |evt|
var dur;
dur = evt[\freq] / 1000
})
).play
)
</pre>
<p>Events are one way you can tie together two keys in an event. You can also do this with arrays:</p>
<pre>
(
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
)
</pre>
<p>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.</p>
<h4>Summary</h4>
<ul>
<li>Event is a subclass of Dictionary.
<li>You can declare an event by just using parenthesis.
<li>You should only use Symbols as keys for Events.
<li>Patterns work by creating events over and over again.
<li>You can access events in Pfunc. It's passed to the function as an argument.
<li>You can use keys in your Event or Pbind that are not meaningful to the Pbind, the Even or the Synth.
<li>Events can be used to tie together two different elements in a Pbind.
<li>Arrays can also be used to tie together two different elements in a Pbind.
</ul>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com4tag:blogger.com,1999:blog-10668379.post-90254518673450046392010-06-25T10:44:00.008-04:002011-08-28T14:37:14.653-04:00Dictionary<p>Let's take a break from Pbinds and their ilk to talk about a data type. A <b>Dictionary</b> is a data type like an array, except that instead of using integers for indexes, you can use anything that you want.</p>
<pre>
(
var id;
id = Dictionary.new;
id.put(\foo, "bar");
id[\foo].postln;
)
</pre>
<p>The indexes are called <b>keys</b> and the items associated with them are called <b>values</b>. In the above example, <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">\foo</span> is the key and <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">"bar"</span> 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.</p>
<pre>
(
var id;
id = Dictionary.new;
id.put(\foo, "bar");
id.put(15, true);
id.put("baz", 12.5);
id[15].postln;
)
</pre>
<p>You can get a list of the keys with the message <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">keys</span>, and then use that to step through a do loop:</p>
<pre>
(
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;
});
)
</pre>
<p>In that example, we see another way of declaring a Dictionary, with square brackets and key, value pairs in the format <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">key -> value</span></p>
<p>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: <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">"string %, % and %".format(var1, var2, var3)</span></p>
<p>Notice that the keys are in a random order. If you want them in a particular order, you will have to sort them.</p>
<p>Here's another example:
<pre>
(
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]);
})
)
</pre>
<p>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.</p>
<p>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.</p>
<p><span class="s3" style="font: normal normal normal 10px/normal Monaco; ">\t</span> means tab and <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">\n</span> means newline. We use these for formatting, to make our output look nice. <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">postf</span> formats a string and then posts it. It does not include a newline, so we do it ourselves with a <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">\n</span></p>
<p><span class="s3" style="font: normal normal normal 10px/normal Monaco; ">Array.sort</span> takes an optional argument, which is a sort function. Here's an example to do a reverse sort:</p>
<pre>
(
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]);
})
)
</pre>
<p>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.</p>
<p>We can check to see if a Dictionary includes a particular key:</p>
<pre>
(
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;
)
</pre>
<p>We can also look for the key of a particular item:</p>
<pre>
(
var id;
id = Dictionary[
\foo -> "bar",
15 -> true,
"baz" -> 12.5
];
id.findKeyForValue(12.5).postln;
)
</pre>
<!--
<p>We can tell IdentityDictionaries to respond to unknown messages as keys:</p>
<pre>
(
var id;
id = IdentityDictionary[
\foo -> 17,
\bar -> pi,
\baz -> 13.5
].know_(true);
id.bar.postln;
)
</pre>
<p>The <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">know_(true)</span> is what makes this so. Note that if we have a key called <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">\at</span>, we cannot use it in this way, because at is a known message to IdentityDictionary.</p>
-->
<h4>Summary</h4>
<ul>
<li>A Dictionary is made up of key, value pairs.</li>
<li>You can add items to a Dictionary with a message <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">put(key, value)</span></li>
<li>Dictionaries can be declared with <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">key -> value</span> pairs in square brackets.</li>
<li><span class="s3" style="font: normal normal normal 10px/normal Monaco; ">Dictionary.keys</span> exports a set of the keys, in random order.</li>
<li>If you want to sort the keys, you must pass them the message <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">.asArray</span> and then pass the message sort to the result of that.</li>
<li>If you want to sort anyhting besides numbers from small ot large you have to write a sort function</li>
<li>A sort function takes two arguments and returns a boolean based on a comparison between them.</li>
<li>You can test is an Dictionary contains a particular key with <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">includesKey</span></li>
<li>You can look up the key for a value with <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">findKeyForValue</span></li>
<!--<li>If you set <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">know</span> to true, you can use keys as messages</li>-->
</ul>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.comtag:blogger.com,1999:blog-10668379.post-46198699054332385942010-06-24T19:35:00.002-04:002010-06-24T19:40:33.411-04:00Streams<p>There's a very useful helpfile set for Streams Patterns and Events, which is available by looking for the helpfile for <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">Streams</span>.</p>
<p>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 <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">next</span>. Here's an example:</p>
<pre>
(
var stream;
stream = Pseq([1, 2, 3], 1).asStream;
3.do({
stream.next.postln;
})
)
</pre>
<p>Any kind of pattern can be converted to a stream by sending it the message <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">asStream</span>. This can be more useful than you might think. For example, if you have two <b>threads</b> stepping through the same data:</p>
<pre>
(
var stream, task1, task2;
stream = Pseq(["Mary", "had", "a", "little", "lamb", "whose", "fleece"], 1).asStream;
task1 = Task({
inf.do({
"task1: ".post;
stream.next.postln;
1.wait;
});
});
task2 = Task({
inf.do({
"task2: ".post;
stream.next.postln;
1.51.wait;
});
});
task1.play;
task2.play
)
</pre>
<p>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:</p>
<pre>
(
var stream, task;
stream = Pseq(["Mary", "had", "a", "little", "lamb", "whose", "fleece"], 1).asStream;
task = { |id, wait|
var next;
Task({
next = stream.next;
{next.notNil}.while({
("task" ++ id ++ ": " ++ next). postln;
wait.wait;
next = stream.next;
});
});
};
task.value(1, 1).play;
task.value(2, 1.51).play
)
</pre>
<p>You can also do math on streams:</p>
<pre>
(
var stream, squared;
stream = Pseq([1, 2, 3], 1).asStream;
squared = stream.squared;
3.do({
squared.next.postln;
})
)
</pre>
<p>And you can do binary math operations on two streams:
<pre>
(
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;
})
)
</pre>
<p>You can use streams with Pbinds, but you have to wrap them in Prout or Pfunc:</p>
<pre>
(
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;
)
</pre>
<p>Note that when notes.next returns nil, the Pbind quits playing.</p>
<h4>Summary</h4>
<ul>
<li>Streams can be create from patterns. The respond to the message next.</li>
<li>When streams run out of values, they start to return nil.</li>
<li>Multiple tasks can access the same stream.</li>
<li>You can do math on streams.</li>
<li>Streams can be used in Pbinds, provided a function or a routine calls next</li>
</ul>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com0tag:blogger.com,1999:blog-10668379.post-39814833096299286442010-06-08T17:46:00.003-04:002010-06-08T17:50:44.701-04:00Math with Patterns & Prout<p>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:</p>
<pre>
(
Pbind(
\dur, 0.2,
\note, Pwhite(0, 6) * 2
).play
)
</pre>
<p>What if you want to square your random numbers?</p>
<pre>
(
Pbind(
\dur, 0.2,
\note, Pwhite(0, 5).squared
).play
)
</pre>
<p>You can do any math operation with a pattern as if it was a number.</p>
<pre>
(
Pbind(
\dur, 0.2,
\note, Pseq([1, 2, 3], 15) * Pseq([1, 2, 3, 5, 4], inf)
).play
)
</pre>
<p>If you want to do math with a pattern and a variable that might change over time, you still need to use a Pfunc:</p>
<pre>
(
var num;
num = 5;
Pbind(
\dur, 0.2,
\note, Pwhite(0, 5) * Pfunc({num})
).play;
Task({
5.wait;
num = 2;
}).play;
)
</pre>
<p>Let's say you want step through every item in a shuffled array. You could use Pseq:</p>
<pre>Pseq([1, 3, 5, 7].scramble, 4)</pre>
<p>Or Pshuf does the same thing:</p>
<pre>Pshuf([1, 3, 5, 7], 4)</pre>
<p>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.</p>
<pre>
(
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
)
</pre>
<p>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.</p>
<p>Like Pfunc, Prout evaluates variables as it runs. In the above example, if arr had changed, the Prout would have used the new arr:</p>
<pre>
(
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;
Task({
2.wait;
arr = [12, 15, 19, 21];
2.wait;
arr = [-12, -13, -11];
}).play
)
</pre>
<p>You could do something similar also, this way:</p>
<pre>
(
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;
)
</pre>
<p>You can have as many yields as you want in a Routine - or a Prout.</p>
<p>If you want to pass in arguments, you can use a wrapper function:</p>
<pre>
(
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
)
</pre>
<p>And, as with Pfunc, you can do math:</p>
<pre>
(
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
)
</pre>
<p>Yielding only works inside Routines. If you try this in a Pfunc, it does not work:</p>
<pre>
(
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
)
</pre>
<p>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.</p>
<h4>Summary</h4>
<ul>
<li>Patterns can behave like numbers for math operations.</li>
<li>A Routine is a function that can pause</li>
<li>A Prout is like a Pfunc, except that it can stop in the midst of things and resume.</li>
<li>Routines can return more than one item, at any point in their execution, whenever you yield a value.</li>
<li>You can only yield in a Routine or a Prout</li>
</ul>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com1tag:blogger.com,1999:blog-10668379.post-64804404271963198212010-06-06T15:23:00.006-04:002010-06-06T15:45:11.411-04:00Pfunc<p>Let's say you want to control some part of your <b>Pattern</b> 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:</p>
<pre>
(
var db, pbind, task;
db = -12;
task = Task({
// ...
5.wait;
60.do({
db = db - 1;
0.1.wait;
});
"done fading".postln;
});
// ...
)
</pre>
<p><span class="s3" style="font: normal normal normal 10px/normal Monaco; ">db</span> 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.</p>
<p><span class="s3" style="font: normal normal normal 10px/normal Monaco; ">task</span> will hold our task. That "..." near the top represents whatever we wanted to do before starting the countdown to the fade-out.</p>
<p>After that, we wait for 5 seconds, then we slowly drop 60 db.</p>
<p>Now for the pbind:</p>
<pre>
// ...
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
);
// ...
</pre>
<p>In the line for degree, we see that we're sending the message <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">pyramid</span> to the array. It reorders the array in an interesting way. See the helpfile for Array for more information about it.</p>
<p>Pbinds understand the symbol <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">\db</span> 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. <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">-12.dbamp</span> is <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">0.25118864315096</span>. Or if you want to go the other way, there's a message ampdb. <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">0.25.ampdb</span> is <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">-12.041199826559</span>. However, the Pbind will do this for you, so you don't need to convert ahead of time.</p>
<p>Now we can try running the task and the pbind simultaneously:</p>
<pre>
// ...
pbind.play;
task.play;
</pre>
<p>And when you put this all together and try it, "done fading" prints out, without there having been any fade.</p>
<p>This is because the interpretter evaluates the expression <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">db</span> 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 <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">db</span>, we need a way to tell the pbind to re-evaluate it every time it comes up. We can do that with <b>Pfunc</b></p>
<p>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:</p>
<pre>
// ...
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});
);
// ...
</pre>
<p>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:</p>
<pre>
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
})
})
);
</pre>
<p>Pbinds stop running as soon as any symbol is paired with <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">nil</span>. Therefore, when <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">db</span> 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.</p>
<p>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 <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">nil</span> or not. If you find it easier to use them everywhere, then you should keep doing that.</p>
<p>We could also skip the false function for the if, since it will still return nil if we do:</p>
<pre>Pfunc({ if(db > -72, { db }) })</pre>
<p>The final version of this example, all together is:</p>
<pre>
(
var db, pbind, task;
db = -12;
task = Task({
// ...
5.wait;
60.do({
db = db - 1;
0.1.wait;
});
"done fading".postln;
});
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;
task.play;
)
</pre>
<h4>Summary</h4>
<ul>
<li>Decibels can be an easier system to use when computing amplitudes</li>
<li>Pbinds will convert between db and amp</li>
<li>The messages ampdb and dbamp can convert number values from amps to db or db to amps</li>
<li>pyramid is an interesting way of shuffling an array</li>
<li>You can put a function in a pattern with Pfunc</li>
<li>A Pfunc with get re-evaluated for every event</li>
<li>A Pbind stops when it gets a nil value</li>
</ul>
<h4>Problem</h4>
<ol>
<li>Write a short piece of music where two separate Pbinds both access the same variable. They can be in the same Ppar or not.</li>
<li>Write a programme such that one Pbind sets a flag that causes another Pbind to change in some way.</li>
</ol>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com0tag:blogger.com,1999:blog-10668379.post-35353463191738122422010-06-05T12:47:00.003-04:002010-06-05T13:00:01.829-04:00Polyphony and Sequencing<h3>Chords</h3>
<p>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:</p>
<pre>Pbind(\note, [1, 3, 5]).play</pre>
<p>The Pbind creates a separate synth for each item in the array.</p>
<p><b>\note</b> 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.</p>
<p>While note is always equally tempered, it need not be 12-tone ET:</p>
<pre>
(
Pbind(
\note, [1, 4, 7],
\stepsPerOctave, 10
).play
)
</pre>
<p>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.</p>
<p>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.</p>
<pre>Pbind(\midinote, 60.05).play</pre>
<p>60.05 is middle C, 5 cents sharp.</p>
<h3>Rests</h3>
<p> If we want to rest for a note, we can do that by pairing the symbol <b>\rest</b> to any of the symbols that control pitch:</p>
<pre>
(
Pbind(
\dur, 0.2,
\note, Prand([1, 4, 7, 9, \rest], 15),
\stepsPerOctave, 10
).play
)
</pre>
<p>We could also pair rest with \freq, \midinote, or \degree - which is the degree in the scale.</p>
<h3>Ppar</h3>
<p>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 <b>Ppar</b>.</p>
<p>Ppar takes two arguments, a list and the number of repeats. Here's an example from the helpfile:</p>
<pre>
(
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;
)
</pre>
<p>a and b play exactly in time with each other.</p>
<p>If we don't want all the patterns to start right away, we can use <b>Ptpar</b>, 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:</p>
<pre>
(
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;
)
</pre>
<p>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</p>
<p>If, instead of playing at the same time, we wanted to play one after the other, we can put the Pbinds into a Pseq:</p>
<pre>
(
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;
)
</pre>
<p>And Pseqs can be passed to Ppars and Ptpars and vice versa.</p>
<h4>Summary</h4>
<ul>
<li>Pairing an array with a symbol in a Pbind makes it play chords</li>
<li>\note determines pitch as a scale degree in an equal tempered scale and can be use with any synthdef.</li>
<li>\degree is the degree in the scale</li>
<li>\stepsPerOctave set the number of pitches in the scale used by \note or \degree</li>
<li>\midinote is the midinote number - in Floats</li>
<li>Pairing \rest with any of pitch-related symbols will cause a rest</li>
<li>We can start two or more Pbinds at the same time with Ppar</li>
<li>We can start two or more Pbinds with a pre-set delay between them using Ptpar</li>
<li>We can start two Pbinds sequentially by putting them in a Pseq</li>
<li>We can put Pseqs in Ppars and vice versa.</li>
</ul>
<h4>Problems</h4>
<ol>
<li>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.</li>
</ol>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com3tag:blogger.com,1999:blog-10668379.post-20898973187458580762010-06-04T15:10:00.005-04:002010-06-04T16:04:17.594-04:00Pbinds<p>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. <b>Pbinds</b> compensate automatically.</p>
<pre>p = Pbind.new.play;</pre>
<p>That will repeat forever until you stop it.</p>
<pre>p.stop;</pre>
<p>A Pbind is a sort of a <b>pattern</b>. 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:</p>
<pre>Pbind(\freq, 660).play</pre>
<p>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:</p>
<pre>Pbind(\freq, 660, \dur, 0.2 + 0.3.rand).play</pre>
<p>Note that the expressions are evaluated when the Pbind's constructor is called. Therefore, whatever value is returned by <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">0.2 + 0.3.rand</span> will be the duration for every separate <b>event</b>.</p>
<p>Repeating the same note over and over is rather dull, so there are some patterns that can help.</p>
<p><b>Prand</b> takes two arguments, an array and the number of times it should run. For example:</p>
<pre>
(
Pbind(
\freq, Prand([330, 440, 660], 6)
).play
)
</pre>
<p>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.</p>
<p>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:</p>
<pre>
(
Pbind(
\freq, Prand([330, 440, 660], 6),
\dur, Prand([0.2, 0.4, 0.3], 5)
).play
)
</pre>
<p>That only plays five notes because the second Prand only will return a value 5 times.</p>
<p>You can also play through a list with <b>Pseq</b>:</p>
<pre>
(
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
)
</pre>
<p>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:</p>
<pre>
(
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
)
</pre>
<p>The lists passed to patterns can contain other patterns:</p>
<pre>
(
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
)
</pre>
<p>You can change what synthdef the Pbind is playing with \instrument. First, let's define a synthdef:</p>
<pre>
(
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
)
</pre>
<p>Then, specify it:</p>
<pre>
(
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
)
</pre>
<p>We can set values for any of the synthdef's arguments:</p>
<pre>
(
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
)
</pre>
<p><b>Pwhite</b> 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.</p>
<p>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.</p>
<pre>
(
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
)
</pre>
<p>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.</p>
<h4>Summary</h4>
<ul>
<li>Pbinds are more accurate than Tasks for playing in time.</li>
<li>Pbinds assume several default values, which you can specify if you want to change them.</li>
<li>Prand(list, n) picks an item from the given list n times.</li>
<li>Pseq(list, n) plays the entire list n times.</li>
<li>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.</li>
<li>Pseqs can contain other patterns, including other Pseqs</li>
<li>You can specify what synthdef to play with \instrument</li>
<li>Pwhite(lo, hi, n) picks a number between low and high n times</li>
<li>Symbols in a Pbind can correspond to synthdef argument names</li>
<li>If you have an unusual argument name, it's a good idea to specify a value for it in the Pbind</li>
</ul>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com3tag:blogger.com,1999:blog-10668379.post-8601997560875449462010-05-31T08:36:00.011-04:002010-05-31T10:26:58.206-04:00Arrays<p>As you've heard many times, a list surrounded by square brackets is an <b>Array</b>. Specifically, it's a comma delineated list of 0 or more elements. Here are some examples:</p>
<pre>
[1]
[x, y, z]
["in", "the", "house"]
[]
</pre>
<p>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.</p>
<pre>
a = Array.new(size);
</pre>
<p>Arrays can hold any kind of object, including numbers, variables, strings or nothing at all. They can even mix types:</p>
<pre>
[3, "French hens", 2 "turtledoves", 1 "partridge"]
</pre>
<p>Arrays can even hold other arrays:</p>
<pre>
[[1, 2, 3], [4, 5, 6]]
</pre>
<p>You can also put an <b>expression</b> in an array. The interpreter evaluates it and stores the results. So <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">[ 3 - 1, 4 + 3, 2 * 6]</span> is also a valid array, stored as <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">[2, 7, 12]</span>. <span class="s4" style="font: normal normal normal 9px/normal Monaco; ">[x.foo(2), x.bar(3)]</span> is also an array. It passes those messages to the objects and puts the result into the array. Because commas have extremely low <b>precedence,</b> they get evaluated after the expressions they separate.</p>
<p>A variable can be part of an expression that is put into an array:</p>
<pre>
(
var foo, bar;
...
[foo + 1 , bar];
)
</pre>
<p>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:</p>
<pre>
(
var foo, arr;
foo = 2;
arr = [foo];
arr.postln;
foo. postln;
" ".postln;
foo = foo + 1;
arr.postln;
foo. postln;
)
</pre>
<p>Outputs:</p>
<pre>
[ 2 ]
2
[ 2 ]
3
3
</pre>
<p>This is <i>almost</i> 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. <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">bar</span> was the last object in the code block, so <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">bar</span> gets returned. <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">bar</span>'s value is 3.</p>
<p>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.</p>
<p>What if we declare a five element array and want to add something to the array? We use the Array.add message.</p>
<pre>
(
var arr, new_arr;
arr = ["Mary", "had", "a", "little"];
new_arr = arr.add("lamb");
arr.postln;
new_arr.postln;
)
</pre>
<p>Outputs:</p>
<pre>
[ Mary, had, a, little ]
[ Mary, had, a, little, lamb ]
</pre>
<p>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. <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">arr</span> doesn’t change in the example because it is already full.</p>
<p>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 <b>scramble</b> and <b>choose</b>.</p>
<p>The helpfile says that scramble "returns a new Array whose elements have been scrambled. The receiver is unchanged."</p>
<p>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 <b>receiver</b> is the object that <b>receives</b> the message "scramble." In the following example, the receiver is <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">arr</span>, which contains <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">[1, 2, 3, 4, 5, 6]</span>.</p>
<pre>
(
var arr, scrambled;
arr = [1, 2, 3, 4, 5, 6];
scrambled = arr.scramble;
arr.postln;
scrambled.postln;
)
</pre>
<p>For me, this output:</p>
<pre>
[ 1, 2, 3, 4, 5, 6 ]
[ 4, 1, 2, 3, 6, 5 ]
</pre>
<p>Of course, the second array is different every time. But <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">arr</span> is always unchanged.</p>
<p>Choose is similar. It picks a random element of the Array and outputs it. The receiver is unchanged.</p>
<pre>
[1, 2, 3].choose.postln;
</pre>
<p>Will output 1, 2 or 3 when you run it.</p>
<p>Arrays are lists, but they are not merely lists. They are <b>index</b>ed lists. You can ask what the value of an item in an array is <b>at</b> a particular position.</p>
<pre>
(
var arr;
arr = ["Mary", "had", "a", "little"];
arr.at(1).postln;
arr.at(3).postln;
)
</pre>
<p>Outputs:</p>
<pre>
had
little
</pre>
<p>Array indexes in SuperCollider start with 0. In the above example, <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">arr.at(0)</span> is <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">"Mary"</span>.</p>
<p>You can also put the index number in square brackets. <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">arr[0]</span> is the same as <span class="s3" style="font: normal normal normal 10px/normal Monaco;">arr.at(0)</span>. If you are using square brackets, you can also modify the contents of the array:</p>
<pre>
(
var arr;
arr = ["Mary", "had", "a", "little", "lamb"];
arr[4] = "giraffe";
arr.postln;
)
</pre>
<p>Arrays also understand the message do, but treat it a bit differently than an Integer does.</p>
<pre>
(
[3, 4, 5].do ({ arg item, index;
("index: " ++ index ++ " item: " ++ item).postln;
});
)
</pre>
<p>Outputs:</p>
<pre>
index: 0 item: 3
index: 1 item: 4
index: 2 item: 5
</pre>
<p>We've called our arguments in this example <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">item</span> and <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">index</span>, 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.</p>
<p>The ++ means <b>concatenate</b>, by the way. You use it to add something to the end of a string or an array. For example:</p>
<p><span class="s3" style="font: normal normal normal 10px/normal Monaco; ">"foo " ++ 3</span> returns the string <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">"foo 3"</span></p>
<p>With arrays, you can use it to add a single item or another array:</p>
<pre>
(
var arr1, arr2, arr3;
arr1 = [1, 2, 3];
arr2 = arr1 ++ 4;
arr3 = arr2 ++ [5, 6];
arr1.postln;
arr2.postln;
arr3.postln;
)
</pre>
<p>Outputs</p>
<pre>
[ 1, 2, 3 ]
[ 1, 2, 3, 4 ]
[ 1, 2, 3, 4, 5, 6 ]
</pre>
<p>Note that the receiver is unchanged.</p>
<p>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:</p>
<pre>
arr.at(index % arr.size);
</pre>
<p>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:</p>
<pre>arr.wrapAt(index);</pre>
<p>It does the modulus for you.</p>
<h4>Musical Example</h4>
<p>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.</p>
<p>She's created SynthDef:</p>
<pre>
(
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
)
</pre>
<p>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.</p>
<p>In the synthdef, one of the SinOscs is modulating the phase of the other SinOsc.</p>
<p>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: <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">[ 1/1, 3/2, 4/3, 9/8, 16/9, 5/4, 8/5 ]</span></p>
<p>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:</p>
<pre>[ 1, 1.5, 1.3333333333333, 1.125, 1.7777777777778, 1.25, 1.6 ]</pre>
<p>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 <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">ratio * baseFreq + detune</span> is not equivalent to <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">detune + ratio * baseFreq</span>, like it would be in algebra. However, fortunately, she can use parenthesis like we would in algebra.</p>
<p>She could write out her <b>expression</b> as <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">(ratio * baseFreq) + detune</span> or <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">(detune + (ratio * baseFreq))</span> 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. </p>
<p>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.</p>
<p>She writes her code as follows:</p>
<pre>
(
var func, arr;
func = { |ratio_arr, baseFreq = 440, detune = 10, dur = 0.2|
Task({
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;
)
</pre>
<p>This is pretty cool, but it always plays out in the same order, so she changes her do loop to: <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">ratio_arr.scramble.do({ |ratio, index|</span></p>
<h4>Summary</h4>
<ul>
<li>You can declare an array by putting a list in square brackets or by using the constructor Array(size)</li>
<li>Arrays can hold any types of objects, all mixed together</li>
<li>You can put an expression into an array. It will hold the result of evaluating the expression.</li>
<li>You can add items to an array by using the add message</li>
<li>The scramble message returns a new array which has the same contents as the receiver, but in a random order</li>
<li>The choose message will return a single element of the receiver, chosen at random</li>
<li>You can access elements of an array with their index: <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">arr.at(index)</span> or <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">arr[index]</span></li>
<li>You can modify a single element of an array with the index: <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">arr[index] = foo</span></li>
<li>You can loop through an array with do: <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">arr.do({|item, index|</span></li>
<li>++ can be used to concatenate strings or arrays</li>
<li>arr.size returns the size of the array</li>
<li>In order to make sure your index is not larger than the size of the array, you can use modulus or wrapAt: <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">arr[index % arr.size]</span> or <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">arr.wrapAt(index)</span>
<li>arguments can be listed inside vertical bars instead of after the word arg: <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">|arg1, arg2|</span> is the same as <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">arg arg1, arg2;</span>
</ul>
<h4>Problems</h4>
<ol>
<li>You can navigate arrays of different length using variables for indexes.</li>
<pre>
(
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;
});
});
)
</pre>
Use this idea to create duration, pitch and wait loops of different lengths. Write a task to pay them</li>
<li>In the <a href="http://sc3howto.blogspot.com/2010/05/while.html">previous post</a>, 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.</li>
</ol>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com0tag:blogger.com,1999:blog-10668379.post-43358890886265415822010-05-30T13:24:00.003-04:002010-05-30T14:28:27.166-04:00While<p>We’ve used Boolean expressions to control the flow of execution of a program with if. Another <b>control structure</b> is <b>while</b>. 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. <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">test_function.while(loop_function);</span> 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. <i>While</i> the condition is true, the loop is executed.</p>
<pre>
(
var counter;
counter = 0;
{counter < 6}.while ({
counter = counter + 3.rand;
counter.postln;
})
)
</pre>
<p><span class="s2" style="font: normal normal normal 10px/normal Monaco; ">{counter < 6}</span> is the test function. If it is true, we run the next two lines inside the while loop.</p>
<p><span class="s2" style="font: normal normal normal 10px/normal Monaco; ">counter = counter + 3.rand;</span> 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.</p>
<p>If instead of <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">counter = 0;</span> we had <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">counter = 7;</span> the test function would have run once, but the loop function would not have run at all.</p>
<p>As with if, functional notation is also common with while. Remember that both notations are entirely equivalent. The following two lines are the same:</p>
<pre>
test_func.while(loop_func);
while(test_func, loop_func);
</pre>
<p>Let's have a musical example, where we track elapsed time rather than the number of notes played. First, we need a synthdef:</p>
<pre>
(
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);
}).load(s);
)
</pre>
<p><span class="s2" style="font: normal normal normal 10px/normal Monaco; ">Formant</span> is an oscillator that creates formants. You can find out more about it in it's helpfile.</p>
<p><span class="s2" style="font: normal normal normal 10px/normal Monaco; ">Pan2</span> 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.</p>
<p>Now, our Task:</p>
<pre>
(
Task({
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
)
</pre>
<p>(This code is translated to SuperCollider from a <a href="http://www.perl.com/lpt/a/2004/08/31/livecode.html">tutorial for making music with Perl</a>.)</p>
<p>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 <b>nil</b>. Nil is not meaningful with a <, nor with any other mathematical or boolean operation.</p>
<p>In our test function, we see if the elapsed duration is less than 20 seconds.</p>
<p>Then in our loop, we add and subtract from a given frequency based on the divisors of a counter.</p>
<p><span class="s2" style="font: normal normal normal 10px/normal Monaco; ">rand2</span> is a message that can be passed to numbers. It returns a random result between (-1 * this) and this. So <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">0.7.rand</span> 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.</p>
<p>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.</p>
<p>The next example is very similar to one from the <a href="http://sc3howto.blogspot.com/2010/05/boolean-expressions.html">previous post</a>.</p>
<pre>
(
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);
}).load(s);
)
(
Task({
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;
)
</pre>
<p>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 <b>tendency masking</b>.</p>
<p>There are other <b>Control Structures</b> detailed in a help file called Control-Structures. Highlight "Control-Structures" and press shift-d</p>
<h4>Summary</h4>
<ul>
<li>While is a control structure that controls a loop</li>
<li>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.</li>
</ul>
<h4>Problems</h4>
<ul>
<li>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.</li>
<ul>
<li>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.</li>
</ul>
</ul>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com0tag:blogger.com,1999:blog-10668379.post-27416546776285367302010-05-29T08:08:00.008-04:002010-05-29T09:44:43.501-04:00Boolean Expressions<p><a href="http://sc3howto.blogspot.com/2010/05/if.html">Last time</a>, 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 <b>boolean expressions</b>.</p>
<p>An <b>expression</b> 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 <b>==</b></p>
<pre>
(
a = 3;
if (a == 3, {
"true".postln;
}, {
"false".postln;
});
)
</pre>
<p>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. </p>
<p>We can test for <b>greater than</b> or <b>less than</b>:</p>
<pre>
(
a = 3;
if (a > 4, {
"true".postln;
}, {
"false".postln;
});
)
</pre>
<pre>
(
a = 3;
if (a < 4, {
"true".postln;
}, {
"false".postln;
});
)
</pre>
<p>We can also test for <b>greater than or equals to</b> and <b>less than or equals to</b>:</p>
<pre>
(
a = 4;
if (a >= 4, {
"true".postln;
}, {
"false".postln;
});
)
</pre>
<pre>
(
a = 3;
if (a <= 4, {
"true".postln;
}, {
"false".postln;
});
)
</pre>
<p>We can also do boolean operations. Some of the most important ones are <b>not</b>, <b>and</b>, and <b>or</b>.</p>
<p>The easiest way to illustrate these is with <b>truth tables</b>. 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:</p>
<table border="1"><tbody></tbody><caption><em>not</em></caption><tbody><tr><th>true</th><th>false</th></tr><tr><td>false</td><td>true</td></tr></tbody></table>
<p>Not is a <b>unary operator</b>. 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. <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">true.not</span> returns false and <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">false.not</span> returns true.</p>
<p><b>And</b> is a <b>binary operator</b>. Like +, -, *, / and %, it operates on two objects. Lets’ say we have two variables, <i>a</i> and <i>b</i>, and either of them can be true or false. We can put <i>a</i> along the top of the table and <i>b</i> down the left side. In the middle we put the possible results of a <b>and</b> b.</p>
<table border="1"><caption><em>and</em></caption><tbody><tr><th></th> <th>true</th><th>false</th></tr><tr><th>true</th><td>true</td><td>false</td></tr><tr><th>false</th><td>false</td><td>false</td></tr></tbody></table>
<p><b>Or</b> is also binary:</p>
<table border="1"><caption><em>or</em></caption><tbody><tr><th></th> <th>true</th><th>false</th></tr><tr><th>true</th><td>true</td><td>true</td></tr><tr><th>false</th><td>true</td><td>false</td></tr></tbody></table>
<p>So how do we code these? Let’s look again at not. Not can be a message sent to a boolean or boolean expression:</p>
<pre>
(
if ((a==4).not , {
"true".postln;
}, {
"false".postln;
});
)
</pre>
<p>You can combine not and equivalency with not equals: <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">!=</span></p>
<pre>
(
a = 2;
if (a != 4 , {
"true".postln;
}, {
"false".postln;
});
)
</pre>
<p>The last two examples are the same.</p>
<p>And is represented by <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">&&</span></p>
<pre>
(
a = 3;
b = 4;
if ( (a > 2) && (b < 5), {
"true".postln;
}, {
"false".postln;
});
)
</pre>
<p>Both <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">(a > 2)</span> <b>and </b><span class="s2" style="font: normal normal normal 10px/normal Monaco; ">(b < 5)</span> must be true for this expression to evaluate as true. If one of them is false, the whole thing is false.</p>
<p><b>Or</b> is represented by <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">||</span> (Those are vertical lines. If you have a Macintosh with an American keyboard, they're over the slash \)</p>
<pre>
(
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;
});
)
</pre>
<p>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.</p>
<h4>Musical Example</h4>
<p>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:</p>
<pre>
(
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);
}).load(s);
)
</pre>
<p>We're trying out a new oscillator called Blip. The helpfile for it says:</p>
<blockquote>
<p><b>Blip.ar(freq, numharm, mul, add)</b></p>
<p>Band Limited ImPulse generator. All harmonics have equal amplitude. This is the equivalent of 'buzz' in MusicN languages. </p>
<p>WARNING: This waveform in its raw form could be damaging to your ears at high amplitudes or for long periods.</p>
</blockquote>
<p>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.</p>
<p>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 <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">env_gen * 3</span> gives us a maximum of 3 harmoics at the peak. If you want more or less, you can change that number. And, of course, <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">env_gen * amp</span> gives us an envelope that goes from 0 to the amp passed in as an argument.</p>
<p>Ok, now for the Task that will play this</p>
<pre>
(
Task({
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;
)
</pre>
<p>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 <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">0.1 + 1.0.rand</span>. 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 <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">1 + 5.0.rand</span>. the the freq is not that low, we go to the false condition and set our variable synth_dur to <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">0.1+ 2.0.rand</span>. We only get to that second false function if both true functions are false. We could re-write those test conditions:</p>
<pre>
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;
});
</pre>
<p>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.</p>
<h4>Summary</h4>
<ul>
<li>An expression is a snippet of code that has a value or can return a value</li>
<li>You can test for equivalency with ==</li>
<li>Greater than is ></li>
<li>Less than is <</li>
<li>Greater than or equal to is >=</li>
<li>Less than or equal to is <=</li>
<li>Not is <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">boolean.not</span> and causes things to invert</li>
<li>Not equals is !=</li>
<li>And is &&. Both conditions must be true for and to be true.</li>
<li>Or is ||. One or both conditions must be true for or to be true.</li>
<li>If statements can be nested</li>
</ul>
<h4>Problems</h4>
<li>Write if statements using <b>and</b>, <b>or</b>, and <b>not</b> using Boolean values of true and false to illustrate the truth tables, using all possible combinations of true and false. For example:
<pre>
(
if (true.not, {
"true".postln;
}, {
"false".postln;
});
)
</pre>
What do you expect each of them to print? Did the results you got from running them match your expectations?</li>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com0tag:blogger.com,1999:blog-10668379.post-46782861861769152112010-05-28T10:56:00.006-04:002010-05-28T11:58:59.650-04:00If<p>In our programmes, we need <b>control structures</b>, that is, ways to make decisions. One control structure is <b>if</b>. <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">if</span> has it's own helpfile. Highlight <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">if</span> and press apple-d. If is also explained briefly in the helpfile for <b>Boolean</b>.</p>
<p>A <b>Boolean</b> is a value that is either true or false. <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">true</span> and <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">false</span> are reserved words in SuperCollider. We can send an <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">if </span>message to Booleans.</p>
<pre>
(
([true, false].choose).if(
{
"true".postln;
}, {
"false".postln;
}
);
)
</pre>
<p>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.</p>
<p>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 <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">[true, false].choose</span> 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.</p>
<pre>boolean.if(trueFunction, falseFunction);</pre>
<p>You can omit the false function if you want.</p>
<p>This syntax that we've been using, <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">object.message(argument1, argument2, . . . argumentN);</span>, is the most commonly used syntax in SuperCollider programs. It's called <b>receiver notation</b>. However, there is more than one correct syntax in SuperCollider. There also exists a syntax called <b>functional notation</b>. 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:</p>
<pre>message(object, argument1, argument2, . . . argumentN);</pre>
<p>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:</p>
<pre>if(boolean, trueFunc, falseFunc);</pre>
<p>So our example would change to:</p>
<pre>
(
if([true, false].choose, {
"true".postln;
}, {
"false".postln;
});
)
</pre>
<p>It works in exactly the same way.</p>
<p>Why are there multiple correct notations? It's confusing!</p>
<p>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.</p>
<p>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.</p>
<p>Let's code an overtone player that has a 50% chance of resting. First, we need a synthdef:</p>
<pre>
(
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);
}).load(s);
)
</pre>
<p>This one uses a sawtooth wave oscillator. Check out the helpfile for <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">Saw</span> for more information.</p>
<p>Then, our player:</p>
<pre>
(
var player;
player = { arg baseFreq, numOvertones, dur = 0.2;
var freq;
Task({
(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;
)
</pre>
<p>If you run it several times, it should rest in different spots, about half the time.</p>
<p>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 <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">[true, true, false].choose</span> 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 <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">0.99.coin</span></p>
<p>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.</p>
<p>The word "this" in that description refers to the number which received the message. If you type 0.66.coin, "this" is 0.66.</p>
<p>Let's give our an example 75% chance of playing a given note:</p>
<pre>
(
var player;
player = { arg baseFreq, numOvertones, dur = 0.2;
var freq;
Task({
(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;
)
</pre>
<h4>Summary</h4>
<ul>
<li>Booleans are either true or false</li>
<li>if is a way of controlling programme flow and making decisions</li>
<li>receiver notation is object.message(argument)</li>
<li>functional notation is message(object, argument)</li>
<li>receiver notation and functional notation are only stylistic differences and both do exactly the same thing</li>
<li>if is often typed as if(boolean, true_function, false_function)</li>
<li>The fase function is optional</li>
<li>The choose message causes an array to pick a single element at random</li>
<li><i>n</i>.coin returns a boolean value with <i>n</i> probability of being true</li>
<li>In helpfiles and other places, "this" refers to the object that received the message</li>
</ul>
<h4>Problems</h4>
<ol>
<li>Re-write <span class="s2" style="font: normal normal normal 10px/normal Monaco; ">"Hello World".postln</span> in functional notation.</li>
<li>Write a programme that has 66% chance of playing the any given note in an arpeggio and a 33% chance of playing a random note instead. You will need to use a false function.</li>
<li>The functions of ifs can contain other ifs. Write a programme that has a 50% chance of playing any given note in arpeggio, a 25% chance of playing a random note and a 25% chance of resting. Remember that if you write if(0.25.coin . . .), it has a 75% chance of picking false and evaluating the false function (if one is present).</li>
</ol>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com1tag:blogger.com,1999:blog-10668379.post-41673384291839600352010-05-27T09:54:00.014-04:002010-06-08T13:47:17.192-04:00Tasks<p><a href="http://sc3howto.blogspot.com/2010/05/envelopes.html">Last time</a>, we learned how to use an envelope to cause synths to stop playing after a set time. Now we're going to look at one way we can control when they start. As with any programming language, there are multiple ways to do this in SuperCollider, each with particular strengths and weaknesses.</p>
<p>We're going to look at something called a <b>Task</b>:</p>
<pre>
(
r = Task.new ({
5.do({ arg index;
index.postln;
1.wait;
});
});
r.play;
)
</pre>
<p>That example prints out:</p>
<pre>
0
1
2
3
4
</pre>
<p>With a one second pause between each number. Try running it.</p>
<p>Remember that the letters a-z are global variables in SuperCollider. Also, remember that the class SimpleNumber is a superclass of both Float and Integer. It can take a message called <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">wait</span>. That message only works in the context of a task (or it's superclasses, like Routine). If we try <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">wait</span> in a normal function:</p>
<pre>
(
f = {
5.do({ arg index;
index.postln;
1.wait;
});
};
f.value;
)
</pre>
<p>We get errors:</p>
<pre>
• ERROR: yield was called outside of a Routine.
ERROR: Primitive '_RoutineYield' failed.
Failed.
</pre>
<p>Tasks (which are a subclass of Routine) are one powerful way to add timing to your program. Task.new takes a function as an argument. It runs that function when we send it the <b>play</b> message. Hence, <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">r.play;</span> in the Task example. When we play a Task, it will pause for a duration of SimpleNumber.wait. If we code <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">5.wait</span>, it will pause for five seconds. If we have <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">0.5.wait</span>, it will pause for half a second.</p>
<p>Ok, now we know how to control when things happen! Let's try this to play some notes! First we need a SynthDef:</p>
<pre>
(
SynthDef.new("example4", {arg out = 0, freq = 440, amp = 0.2,
dur = 1;
var square, env_gen, env;
env = Env.triangle(dur, amp);
env_gen = EnvGen.kr(env, doneAction:2);
square = Pulse.ar(freq, 0.5, env_gen);
Out.ar(out, square);
}).load(s);
)
</pre>
<p>This is just like our last SynthDef, except that it uses a square wave instead of a sine wave. To find out more about the Pulse UGen, read the help file on it.</p>
<p>Ok, let's play some pitches. the range of human hearing is 20Hz - 20,000 Hz, but the range of my laptop speakers is somewhat less than that, so let's pick between 200 - 800 Hz.</p>
<pre>
(
Task({
var freq;
10.do({
freq = 200 + 600.rand;
Synth(\example4, [\out, 0, \freq, freq, \dur, 0.5]);
0.5.wait;
});
}).play;
)
</pre>
<p>When you we that, we get random pitches.</p>
<p>In the first line, you'll notice that we just have <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">Task({</span> instead of <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">Task.new({</span>. This is a shortcut that SuperCollider allows. You can just have Class(argument1 , argument2 . . .) in place of Class.new(argument1, argument2 . . .). The <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">.new</span> is implied.</p>
<p>The next line with something new is <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">freq = 200 + 600.rand;</span>. You can pass the message <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">rand</span> so a SimpleNumber. It will return a random number between 0 and the number that it's passed to. So <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">600.rand</span> will return a random number between 0 - 600. If we add 200 to that number, then we have a random number between 200 - 800, which is the range we want.</p>
<p>In the past, we <a href="http://sc3howto.blogspot.com/2010/05/numbers-and-math.html">talked a bit about precedence</a>. In SuperCollider, passing messages will be evaluated before math operations like addition, subtraction, etc. So the interpreter will evaluate 600.rand first and then add 200. Therefore, we will get the same results if we type <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">freq = 200 + 600.rand;</span> or if we type <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">freq = 600.rand + 200;</span></p>
<p>In the next line, we've got <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">Synth(\example4</span> instead of <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">Synth.new(\example4</span>. This is the same shortcut as in the first line.</p>
<p>In that example, we pass 0.5 to the synth for it's duration and wait 0.5 seconds, so there's no overlap between the notes. We don't have to do it that way. We could only wait for 0.25 seconds and let the notes overlap, or we could extend the wait and leave spaces between the notes. Or we could change the Synth duration. We could use random numbers for waits and durations:</p>
<pre>
(
Task({
var freq;
10.do({
freq = 200 + 600.rand;
Synth(\example4, [\out, 0, \freq, freq, \dur, (0.1+ 2.0.rand)]);
(0.01 + 0.4.rand).wait;
});
}).play;
)
</pre>
<p>The two parts that have changed are <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">\dur, (0.1+ 2.0.rand)</span> and <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">(0.01 + 0.4.rand).wait;</span>. The reason that we have 2.0.rand is because Integer.rand returns an Integer and Float.rand returns a float. 2 is an integer, so 2.rand will return either 1 or 0 and no other numbers. 2.0.rand, however, will return real numbers and thus can return things like 0.72889876365662 or 1.6925632953644. Try evaluating 2.rand and 2.0.rand several times and look at the results you get.</p>
<p>We use parenthesis in <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">(0.01 + 0.4.rand).wait;</span> so that we sent the wait message to the results of 0.01 + 0.4.rand. If we were to skip the parenthesis, we would pick a random number between 0 and 0.4 and then wait that long and then add 0.01 to the results of the wait message, which is not what what we want. We add in that 0.01 to make sure that we never have a wait of 0. This is an aesthetic decision. 0.wait is perfectly acceptable.</p>
<p>What if we want to modify the number of times we run through our main loop? We can't pass arguments to a Task, but fortunately, because of <b>scope</b> and functions <b>returning</b> things, there is a clever work around:</p>
<pre>
(
var func, task;
func = { arg repeats = 10;
Task({
var freq;
repeats.do({
freq = 200 + 600.rand;
Synth(\example4, [\out, 0, \freq, freq, \dur, (0.1+ 2.0.rand)]);
0.01 + 0.4.rand.wait;
});
});
};
task = func.value(15);
task.play;
)
</pre>
<p>First, we write a function that takes an argument. Then, inside the function, we have a Task. Because the Task is inside the function's code block, the Task is within the scope of the argument. And because the Task is the last (and only, aside from the args) thing inside the function, it gets returned when the function gets evaluated. So <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">task</span><span class="s4" style="font: normal normal normal 9px/normal Monaco; "> </span>gets the Task that is returned by the function. Then we call <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">task.play;</span> to run the Task. It's ok to have a variable called task because SuperCollider is case-sensitive and therefore Task, task, tASK, taSk, etc are all different.</p>
<p>Remember that functions <b>return</b> their last value. And remember that <b>scope</b> means that inner code blocks can see variables from outer code blocks, but not vice versa. So the Task can see the args. And there's nothing after the Task in the function, so it's the last value, so it gets returned when we send a value message to the function. Then we send a play message to the returned Task. We could abbreviate the last two lines of our program by just having one line:</p>
<pre>func.value(15).play;</pre>
<p >The interpreter, reading from right to left, will pass a value message to the func, with an argument of <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">15</span>. That returns a Task, which is then passed a message of play.</p>
<p></p><h4>Summary</h4>
<ul>
<li>Tasks are functions that can pause.</li>
<li>In a task, <i>number</i>.wait will pause for that number of seconds.</li>
<li>You cannot ask a code block to wait unless it is within a a Routine, which is a superclass of Task.</li>
<li><i>n</i>.rand returns a number between 0 and <i>n</i>. If <i>n</i> is an integer, it returns an integer. If <i>n</i> is a float, it returns a float.</li>
<li>You cannot pass arguments to Tasks, but you can put them in functions that take arguments and then return the Task from the function.</li>
</ul>
<h4>Problems</h4>
<ol>
<li>Write a a task that plays an arpeggio of the first <i>n</i> overtones over a base frequency. Use a wrapper function to pass in both the frequency and the number of overtones. Give the arguments descriptive names. (There is an explanation of overtones in the <a href="http://sc3howto.blogspot.com/2010/05/numbers-and-math.html">post on numbers</a>.)</li>
<li>Write a task that produces <i>n</i> separate sound clusters. Pass that number as an argument (using functions). Give the argument a descriptive name.</li>
</ol>
<h4>Project</h4>
<ol>
<li><p>Write a short piece that uses tone clusters that are in different frequency ranges. For example, one section might be 100-300 Hz and another might be 600-1200 Hz. You may wish to vary the timbres by using multiple synthdefs. You may wish different sections to have different densities, also.</p>
<p>You can make a recording of your piece by pressing the "Prepare Record button" on the server window, after you boot it. It will turn red and say "record >". Press it again to start recording. The button will change color again and say "stop []". this means it's now recording. Run your piece. Click the button again when your piece has finished to stop recording. The Recording will go in to your home directory under Music/SuperCollider Recordings. It will be a 32 bit aiff, but you can convert it to a 16bit aiff or to mp3 with <a href="http://audacity.sourceforge.net/">Audacity</a>.</p>
<p>If you do this project, please feel free to share your results in the comments!</p></li>
</ol>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com1tag:blogger.com,1999:blog-10668379.post-39836573163410199292010-05-26T08:43:00.006-04:002010-05-26T09:20:20.039-04:00Envelopes<p>In the <a href="http://sc3howto.blogspot.com/2010/05/numbers-and-math.html">last post</a>, we wrote a function to play overtones, but it played them all at the same time. In order to write a piece of music, we need both to be able to tell notes when to start and for how long they should last. This section will be on the latter part of the problem.</p>
<blockquote>
<p>"Just like human beings, sounds are born, reach their prime and die; but the life of a sound, from creation to evanescence last only a few seconds"
Yamaha GX-1 Guide</p>
</blockquote>
<p> We control this process with a type of UGen called an <b>envelope</b>. </p>
<pre>
(
SynthDef.new("example3", {arg out = 0, freq = 440, amp = 0.2,
dur = 1;
var sin, env_gen, env;
env = Env.triangle(dur, amp);
env_gen = EnvGen.kr(env);
sin = SinOsc.ar(freq, mul: env_gen);
Out.ar(out, sin);
}).load(s);
)
Synth.new("example3");
</pre>
<p>There are a few things that make that SynthDef different. One is that it uses variables. Variables are a good way to keep SynthDefs more readable. The easier it is to read, the easier it is to understand, to fix and to change.</p>
<p>The other obvious change is the addition of an envelope. Envelopes have two parts. One is <b>Env</b>. The Env class lets you describe what shape the envelope should have. In this case, we're using a <b>fixed duration</b> envelope shaped like a triangle. When we use a fixed duration envelope, we know the length of the envelope when we create an instance of the Synth. There are other envelopes that we will not know the envelope of until we decide to end the note, for instance, in response to a key up on a keyboard.</p>
<p><span class="s3" style="font: normal normal normal 10px/normal Monaco; ">triangle</span> is a constructor. It creates a new instance of an Env. The arguments it takes are the duration and the maximum amplitude.</p>
<p>The other part of the envelope is the<span class="s7" style="font: normal normal normal 12px/normal Helvetica; "><b> </b></span><b>EnvGen</b>. Since EnvGen is a class, <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">kr</span> must be a constructor. The two most common UGen constructors are <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">ar</span> and <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">kr</span>. You may recall that ar stands for “audio rate.” kr stands for “control rate.” Because the EnvGen is not actually creating sound, but is controlling the amplitude of a sound, we want the control rate. Control rate signals change less often than audio rate signals, and so using kr reduces the load on our computer and makes our SynthDef more efficient. </p>
<p>EnvGen.kr generates the envelope based on the specifications of its first argument, an instance of Env. So, with Env, we define an Envelope. We pass that definition to an Envelop Generator, which plays back the envelope that we defined. We use that envelope to control the amplitude of a SinOsc. We send the output of the SinOsc to an output bus. When the envelope is done, the amplitude of it has returned to zero, so the SinOsc is no longer audible.</p>
<p>With our previous examples, the Synth never ended. The way to stop sound was to stop execution with apple-. . With our new SynthDef, the sound goes on for exactly the length of dur and then ends with no way to restart it. After we create a Synth and play it, there's nothing that can be done with it.</p>
<p>Try running <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">Synth.new("example3");</span> several times. If you look at the localhost server window, you will see the number of UGens and Synths grow every time you run Synth.new. The Avg and Peak CPU may also increase.</p>
<p>Every time we create a new instance of Synth, we use up more system resources. Eventually we will either run out of memory or the CPU will climb over 100%. We can clear the Synths by hitting apple-., but this still would limit the number of sounds we could play in a row without stopping execution.</p>
<p>We need an automatic way to remove our synths from the server and <b>deallocate</b> their resources. That means that some new Synths would be able to use the resources the old ones were taking up.</p>
<p>Fortunately, EnvGens can both silence a Synth forever and lay it to rest so iti s deallocated. EnvGen takes an argument called “doneAction”. Adding a <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">doneAction</span> to your EnvGen would look like:</p>
<pre>env_gen = EnvGen.kr(env, doneAction: 2);</pre>
<p>Try changing adding a doneAction to the SynthDef and running <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">Synth.new("example3");</span> a few times. Notice that now the Synths don’t accumulate. Now, after a Synth stops making sound, it has ended its useful life and so it gets removed from the server because of the <span class="s3" style="font: normal normal normal 10px/normal Monaco; ">doneAction: 2</span>. However, note that the doneAction removes only instances of the Synth. The SynthDef persists and can be used as many times as we'd like.</p>
<p>Envelopes don’t have to only control amplitude, but can control (almost) any aspect of any UGen. You can’t set the bus on Out.ar with an Envelope, but you can control almost anything else. For example, we can cause the frequency to warble</p>
<pre>
(
SynthDef.new("example3a", {arg out = 0, freq = 440, amp = 0.2,
dur = 1;
var sin, env_gen, env, freq_env;
env = Env.triangle(dur, amp);
env_gen = EnvGen.kr(env, doneAction: 2);
freq_env = EnvGen.kr(Env.sine(dur, 50));
sin = SinOsc.ar(freq + freq_env, mul: env_gen);
Out.ar(out, sin);
}).load(s);
)
Synth.new("example3a");
</pre>
<p>Note that we only need one of the envelopes to have a doneAction.</p>
<h4>Summary</h4>
<ul>
<li>Envelopes can be used to control how the amplitude of a Synth changes over time.
<li><span class="s3" style="font: normal normal normal 10px/normal Monaco; ">Env</span> is used to describe the shape of an enevelope.
<li><span class="s3" style="font: normal normal normal 10px/normal Monaco; ">EnvGen.kr</span> is what actually plays the envelope.
<li>Synths can be deallocated by using the doneAction argument of EnvGen.
<li>Envelopes can also be used to control frequency and many other parameters of SynthDefs.
</ul>
<h4>Problems</h4>
<ol>
<li>Try out the different fixed duration envelopes and try them out with different Oscillators. Especially try out the Env.perc envelope with different noise generators.</li>
</ol>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com0tag:blogger.com,1999:blog-10668379.post-69763172346626223552010-05-24T09:55:00.008-04:002010-05-24T10:52:53.867-04:00Numbers and Math<p>In the <a href="http://sc3howto.blogspot.com/2010/05/functions.html">previous post</a>, we talked a bit about Integers, which, remember are whole numbers, like -1, 0, 1, 2. And we learned about the do message.</p>
<p>What are some things you might want to do to a number? Add, subtract, multiply, divide, modulus.</p>
<p>Remember algebra where a*b + c*d = (a * b) + (c * d). And remember how that one cheap calculator just did what you punched in, in the order you punched it in, without respecting order of operations? SuperCollider is like that cheap calculator. Mathematical expressions are evaluated left to right. Addition and subtraction have the same <b>precedence</b> as multiplication and division. That means that if you want to do things in some order, you've got to use parenthesis.</p>
<p>Parentheses are evaluated innermost to outermost:<br />
(a + (b * (c + d)))<br />
( 2 + (4 * (3 + 2))) = (2 + (4 *(5))) = (2 + (20)) = 22</p>
<p>What about order of operations within longer lines of code? If we have<span class="s4" style="font: normal normal normal 12px/normal Helvetica; "> </span><span class="s6" style="font: normal normal normal 10px/normal Monaco; ">func.value(3+4)</span>, it evaluates <span class="s6" style="font: normal normal normal 10px/normal Monaco; ">3+ 4</span><span class="s4" style="font: normal normal normal 12px/normal Helvetica; "> </span>to<span class="s4" style="font: normal normal normal 12px/normal Helvetica; "> </span><span class="s6" style="font: normal normal normal 10px/normal Monaco; ">7</span><span class="s4" style="font: normal normal normal 12px/normal Helvetica; "> </span>before calling the function. We can put anything we want inside those parentheses and it will evaluate what's inside until it gets to the outermost parenthesis and then it will call the function.</p>
<p>One math operation that you might not have seen before is <b>modulus</b>. It means "remainder" and it's represented by a '%'.<br />
10 % 3 = 1<br />
26 % 9 = 8</p>
<p>Ok, so the output of a modulus between two integers is an integer, by definition. And if you add or subtract two integers, you get an integer. As you do if you multiply two integers. But what is the result of division? <br />
3 / 2 = 1.5</p>
<p>1.5 is not an integer. It's a type of number called a Floating point, or in SuperCollider, a <b>Float</b>. A float is a fraction. 1.1, 2.5, -0.2, 5.0 are all Floats. They also can add subtract, etc.</p>
<p>You can do more with numbers than simple math and do loops. There are many interesting and useful messages one can pass to Integer. It has a help file worth reading. So type in the word Integer, starting with a capital-I and press apple-d to look at the help file. The top of that help file says:</p>
<p class="p3" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; text-align: justify; font: normal normal normal 12px/normal 'Helvetica Neue'; font-family: Times; font-size: medium; "><b>superclass: SimpleNumber</b></p>
<p><b>superclass</b> is a vocabulary word. It refers to a concept called <b>inheritance</b>. What this superclass designation means is that Integer <b>is a</b> SimpleNumber. When you define classes (recall that a class is the definition for an object), you can define <b>subclasses</b> of any class. A subclass is a special type of the original class. It <b>inherits</b> all the properties of its <b>superclass</b>. So the subclass is the child and the superclass is the parent. We'll come back to this. But what it means for us is that Integer <b>is a</b> SimpleNumber. Which means it understands all the messages that you can pass to a SimpleNumber. So to find out about what these inherited messages are, we should highlight "SimpleNumber" and hit apple-d Float and Integer both inherit from SimpleNumber, so take a look at that help file. Looking at help files and trying stuff out will get you learning the language faster than anything else. They might not make a lot of sense right now, but if you keep looking, you'll get context and be able to figure them out in the future.</p>
<p>We have one more example that hopefully ties all of this together. Remember our <a href="http://sc3howto.blogspot.com/2010/05/synthdefs.html">SynthDef from posts past</a>? Here's an updated version of it.</p>
<pre>
(
SynthDef.new("example2", {arg freq = 440, amp = 0.2;
Out.ar(0, SinOsc.ar(freq, mul: amp));
}).load(s);
)
</pre>
<p>We’ve added a field called amp, which indicates the <b>amplitude</b> or volume at which the sound should play. In SuperCollider, amplitudes louder than 1 will peak when you listen to them. Therefore output amplitudes should be between 0, which is silent, and 1, which is as loud as possible.</p>
<p>Now, lets’ write some code to play <i>N</i> overtones of 100Hz. We need to make sure that our overall amplitude doesn’t exceed 1, or else we’ll get peaking. So, we will divide 1 by the number of overtones into 1 to get the amp value to send to each synth. </p>
<pre>
(
var func;
func = { arg repeats = 4;
repeats.do({ arg index;
Synth.new("example2", [\freq, (index + 1) * 100,
\amp, 1 / repeats]);
});
};
func.value;
)
</pre>
<p>Let's hear what happens when we play this. All the sounds play at once! This is because the loop goes through as fast as it can. We'll cover timing issues very soon.</p>
<h4>Summary</h4>
<ul>
<li>Whole numbers are Integers
</li><li>Real numbers are Floats
</li><li>You can indicate order of operations with parenthesis
</li><li>Math operations are evaluated innermost to outermost parenthesis and left to right
</li><li>Modulus (%) means remainder
</li><li>Subclasses inherit the properties of their superclasses - an Integer is a SimpleNumber
</li><li>Output amplitudes should be between 0 and 1.
</li></ul>
<h4>Problems</h4>
<ol>
<li>Translate the following algebraic expressions into proper supercollider syntax, using parenthesis where needed. Try to make your answers human-readable.
<ol type="a">
<li>3 + 5 * 4
</li><li>7 * 2 + 1
</li><li>6 * (4 + 2)
</li><li>2 * 3 + 4 * 5 + 7 / 2 + 1
</li>
</ol>
</li><li>Get yourself familiar with modulus by working out these problems by hand.
<ol type="a">
<li>5 % 4
</li><li>163 % 9
</li><li>20 % 5
</li><li>17 % 6
</li><li>23 % 2
</li><li>3 % 5
</li>
</ol>
</li><li><p>Write a function to print out the first n multiples of 10, starting from 0. Pass the number of multiples into the function as an argument. Set the default number to 7.</p>
<li><p>Write a function that takes three arguments, <span class="s15" style="font: normal normal normal 12px/normal Courier; ">numberOfOvertones</span>, <span class="s15" style="font: normal normal normal 12px/normal Courier; ">pitch</span> and <span class="s15" style="font: normal normal normal 12px/normal Courier; ">amp</span>. It should play the number of overtones above <span class="s15" style="font: normal normal normal 12px/normal Courier; ">pitch</span> specified by the argument <span class="s15" style="font: normal normal normal 12px/normal Courier; ">numberOfOvertones</span>. The amplitude of the overtones should be half the amplitude of the fundamentals and the total amplitude for the fundamental plus the overtones should be <span class="s15" style="font: normal normal normal 12px/normal Courier; ">amp</span>.</p></li>
<li><p><span class="s15" style="font: normal normal normal 12px/normal Courier; ">rand</span> is a message that you can send to numbers. <span class="s6" style="font: normal normal normal 10px/normal Monaco; ">y.rand</span> returns a number between 0 and y. Humans are generally able to hear frequencies between 20Hz and 20000Hz (the freq argument for oscillator UGens is in Hz). Write a function that calls your previous function. You want to play <i>n</i> random pitches and the first <i>m</i> overtones of those pitches. Make sure that the random pitches are all in the audible range. Pass the number of random pitches and the number of overtones into your new function as arguments. Set the default number of random pitches to 2 and the default number of overtones to 3. Make certain that your total amplitude will not peak. Finally, give the arguments descriptive names.</p></li>
<ol type="a">
<li>Can you figure out a way to make sure that all your pitches, including overtones, are in the audible range?
</ol>
</ol>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com0tag:blogger.com,1999:blog-10668379.post-70672846504406671652010-05-23T10:07:00.009-04:002010-05-23T14:00:02.334-04:00Functions<p c="">After reading the <a href="http://sc3howto.blogspot.com/2010/05/synthdefs.html">last chapter on SynthDefs</a> and the one <a href="http://sc3howto.blogspot.com/2009/12/variables.html">before that on Variables</a>, Nicole feels like she's got the hang of SuperCollider so she's dropped out of grad school to work for the new SuperCollider start-up company SuperSounds.com. On her first day, her boss tells her to write a function that prints "hello world" four times. "No problem," she thinks and goes to look at previous posts. <b>Functions</b> are code blocks encased by curly brackets, { } and hello world is easy enough. So she writes:</p>
<pre>
(
{
var greet;
greet = "hello world";
greet.postln;
greet.postln;
greet.postln;
greet.postln;
}
)
</pre>
<p>Then she thinks, "I should have asked for a signing bonus." She tries running it, by double clicking to the right of the top parenthesis and hitting enter. In the Untitled output window it says,<span class="s4" style="font: normal normal normal 12px/normal Helvetica; "> </span><span class="s5" style="font: normal normal normal 10px/normal Helvetica; ">"</span><span class="s6" style="font: normal normal normal 10px/normal Monaco; ">a Function</span><span class="s5" style="font: normal normal normal 10px/normal Helvetica; ">"</span></p>
<p>What's the problem? She declared a variable called<span class="s4" style="font: normal normal normal 12px/normal Helvetica; "> </span><span class="s6" style="font: normal normal normal 10px/normal Monaco; ">greet</span><span class="s4" style="font: normal normal normal 12px/normal Helvetica; ">. </span><span class="s6" style="font: normal normal normal 10px/normal Monaco; ">greet</span><span class="s4" style="font: normal normal normal 12px/normal Helvetica; "> </span>gets<span class="s4" style="font: normal normal normal 12px/normal Helvetica; "> </span><span class="s7" style="font: normal normal normal 10px/normal Monaco; color: rgb(115, 115, 115); ">"hello world"</span><span class="s4" style="font: normal normal normal 12px/normal Helvetica; ">. </span>Then she sends a<span class="s4" style="font: normal normal normal 12px/normal Helvetica; "> </span><span class="s6" style="font: normal normal normal 10px/normal Monaco; ">postln</span><span class="s4" style="font: normal normal normal 12px/normal Helvetica; "> </span>message to<span class="s4" style="font: normal normal normal 12px/normal Helvetica; "> </span><span class="s6" style="font: normal normal normal 10px/normal Monaco; ">greet</span><span class="s4" style="font: normal normal normal 12px/normal Helvetica; "> </span>four times. Every line ends with a semicolon . . .</p>
<p>Then she realizes that she defined a function, but never told the interpreter to run it. The interpreter saw a code block surrounded by curly brackets and thought "a function!" Then it thought, "What do you want me to do with this? Nothing? Ok, I'll throw it away." So Nicole modifies her code:</p>
<pre>
(
var func;
func = {
var greet;
greet = "hello world";
greet.postln;
greet.postln;
greet.postln;
greet.postln;
};
func.value;
)
</pre>
<p>And then it works great.<span class="s4" style="font: normal normal normal 12px/normal Helvetica; "> </span><span class="s6" style="font: normal normal normal 10px/normal Monaco; ">value</span><span class="s4" style="font: normal normal normal 12px/normal Helvetica; "> </span>is a message you can send to functions. It means, "Run yourself!"</p>
<p>But then Nicole gets a message from her boss saying, "Sometimes, we need to print out hello world five times and once in a while, three times, and rarely, it needs to print out infinite times." Nicole considers writing a few different versions of the function and calling them func4, func3, etc, but then remembers about <b>arguments</b> to functions.</p>
<pre>
(
var func;
func = { arg repeats;
var greet;
greet = "hello world";
repeats.do ({
greet.postln;
});
};
func.value(4);
)
</pre>
<p>When she writes her function, she <b>declares</b> to the interpreter that the function takes one argument. An argument is a special type of variable that gets set when the function is called. When she calls the function with<span class="s4" style="font: normal normal normal 12px/normal Helvetica; "></span><span class="s6" style="font: normal normal normal 10px/normal Monaco; ">func.value(4);</span>, she's assigning a value to the argument<span class="s4" style="font: normal normal normal 12px/normal Helvetica; "> </span><span class="s6" style="font: normal normal normal 10px/normal Monaco; ">repeats</span><span class="s4" style="font: normal normal normal 12px/normal Helvetica; ">.</span></p>
<p>Then, inside the function, she's written,<span class="s4" style="font: normal normal normal 12px/normal Helvetica; "> </span><span class="s6" style="font: normal normal normal 10px/normal Monaco; ">repeats.do</span><span class="s4" style="font: normal normal normal 12px/normal Helvetica; ">. </span>What is 'do'? It's a message. It takes a function as an argument. 'do' is a message you can send to <b>integers</b> that runs the function passed as an argument the number of times as the integer that it was called on. In this example, repeats is 4, so it runs four times.</p>
<p>What is an integer? An integer is a whole number. -2, -1, 0, 1, 2, 3, 4, etc. There is a special integer in SuperCollider called inf. It means infinity. If we try calling our above function, with</p>
<pre>func.value(inf);</pre>
<p>hello world will print out forever, or until we stop the program by hitting apple-. .</p>
<p>Then Nicole's boss sends another email saying that marketing has some changes. Every line needs to start out with the line number, starting with zero. So she makes another change:</p>
<pre>
(
var func;
func = { arg repeats;
var greet;
greet = "hello world";
repeats.do ({ arg index;
index.post;
" ".post;
greet.postln;
});
};
func.value(4);
)
</pre>
<p>The function called by do takes an argument. And that argument is the number of times the loop has been run, starting with 0. So her output from this program is:</p>
<pre>
0 hello world
1 hello world
2 hello world
3 hello world
</pre>
<p><span class="s6" style="font: normal normal normal 10px/normal Monaco; ">post</span> just means print without a new line at the end. </p>
<p>Almost every time, she runs this function, the argument is going to be 4. So she can declare a default argument for the function.</p>
<pre>
(
var func;
func = { arg repeats = 4;
var greet;
greet = "hello world";
repeats.do ({ arg index;
index.post;
" ".post;
greet.postln;
});
};
func.value;
)
</pre>
<p>When she calls <span class="s6" style="font: normal normal normal 10px/normal Monaco; ">func.value</span>, if there's no argument, then the interpreter will assign 4 to repeats by default. If she calls it with,<span class="s4" style="font: normal normal normal 12px/normal Helvetica; "> </span><span class="s6" style="font: normal normal normal 10px/normal Monaco; ">func.value(6</span><span class="s8" style="font: normal normal normal 10px/normal 'Helvetica Neue'; ">);</span><span class="s9" style="font: normal normal normal 9px/normal 'Helvetica Neue'; "> </span>then repeats gets 6 instead. What if she accidentally passes in something besides an Integer into her function? That depends. If the object she passes in also understands a do message, then it will use that instead, although the result may differ. Otherwise, she will get an error.</p>
<p>What if the function took a lot of arguments with default values?</p>
<pre>
(
var func;
func = { arg foo = 0, bar = 0, baz = 1, repeats = 4;
var greet;
greet = "hello world";
repeats.do ({ arg index;
index.post;
" ".post;
greet.postln;
});
};
func.value;
)
</pre>
<p>If she wants to pass in arguments, she does it in the order they're declared in.</p>
<pre>func.value(0 /* foo */, 0 /* bar */, 1 /* baz */, 3 /* repeats */);</pre>
<p>However, if we're happy with all the default values, there's a way to tell the function just to assign to a particular variable, out of order:</p>
<pre>func.value(repeats: 3);</pre>
<p>You can also just pass in the first N arguments and leave the remainder to the default values:</p><p class="p4" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; text-align: justify; font: normal normal normal 12px/normal Helvetica; min-height: 14px; font-family: Times; ">
</p><p class="p5" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; text-align: justify; font: normal normal normal 10px/normal Monaco; font-family: Times; ">func.value(3, 1);</p>
<p>And you can combine approaches:</p>
<pre>func.value(2, repeats: 6);</pre>
<p>Those slash-stars up there are <b>comments</b>. The interpreter ignores everything between a forward slash star and a backslash star. They can span multiple lines. You can also create single line comment by using forward slash forward slash:</p>
<pre>// This is a comment</pre>
<p>Some times it's useful to <b>comment out</b> a line of code while <b>debugging</b>. So you can skip a particular line in order to figure out where your error is.</p>
<p>The philosophical point of a function is to <b>return</b> a value. Doing things within functions, like printing are technically called <b>side effects</b>. What the function returns is the value of its last line. Let's change that function so it returns the number of times that it printed.</p>
<pre>(
var func;
func = { arg repeats = 4;
var greet;
greet = "hello world";
repeats.do ({ arg index;
index.post;
" ".post;
greet.postln;
});
repeats;
};
func.value;
)
</pre>
<p>Now, if we create a new variable called <span class="s6" style="font: normal normal normal 10px/normal Monaco; ">times</span>, we can assign the output of the function to it.</p>
<pre>
(
var func, times;
func = { arg repeats = 4;
var greet;
greet = "hello world";
repeats.do ({ arg index;
index.post;
" ".post;
greet.postln;
});
repeats;
};
times = func.value;
times.postln;
)
</pre>
<p>Prints out hello world with the line number like before, and then at the bottom, prints out a 4. Or we could change those last two lines from</p>
<pre>
times = func.value;
times.postln;
</pre>
<p> to</p>
<pre>func.value.postln;</pre>
<p>and the interpreter will read that statement left to right, first finding the value of the function and then sending that value a postln message.</p>
<p>Ok, what happens if we take the above function and write some code below it that looks like this:</p>
<pre>
(
var func, times;
func = { arg repeats = 4;
var greet;
greet = "hello world";
repeats.do ({ arg index;
index.post;
" ".post;
greet.postln;
});
repeats;
};
greet.postln;
)
</pre>
<p>We get errors.</p>
<pre>
• ERROR: Variable 'greet' not defined.
in file 'selected text'
line 14 char 6 :
greet•.postln;
</pre>
<p>This is because of something called <b>scope</b>. Variables only exist in the code block in which they are declared. Code blocks are zero or more lines of code surrounded by curly braces or highlighted by the user. This means that variables and arguments declared inside a function only exist inside that function. <span class="s6" style="font: normal normal normal 10px/normal Monaco; ">index</span> does not exist outside of its function, which is the function passed as an argument to <span class="s6" style="font: normal normal normal 10px/normal Monaco; ">repeats.do</span>. <span class="s6" style="font: normal normal normal 10px/normal Monaco; ">greet</span> does not exist outside of it's function. None of these variables exist of the text we highlight.</p>
<p>Variables in outer blocks are accessible within inner blocks. For example,</p>
<pre>
(
var func, times;
times = 0;
func = { arg repeats = 4;
var greet;
greet = "hello world";
times.postln;
repeats.do ({ arg index;
index.post;
" ".post;
greet.postln;
});
repeats;
};
)
</pre>
<p >Is fine because <span class="s6" style="font: normal normal normal 10px/normal Monaco; ">times</span> exists in the outer most block. In the same way, we can use greet inside our repeats.do function.</p>
<p>There are, however, a few variables that can be used everywhere. The interpreter gives us 26 <b>global variables</b>. Their scope is all of SuperCollider. They are single letter variable names, a, b, c, d, e, f, etc. You don't need to declare them and they keep their value until you change it again, even in different code blocks. This is why the variable 's' refers to the Server. You can change that, but you might not want to. </p>
<p>If you have any questions about functions, you can look at the <span class="s11" style="font: normal normal normal 9px/normal Monaco; ">Function</span> help file for more information. The most useful message you can send to a function is value, but there are a few others, which you can read about. You may not understand everything you see in the helpfiles, but it’s good to keep reading them.</p>
<h4>Summary</h4>
<ul>
<li>Blocks of code surrounded by curly brackets are functions.
</li><li>Functions do not run unless you tell the interpreter to run them, which you can do with the message "value".
</li><li>You can declare arguments to function. That argument can have a default value.
</li><li>An integer is a whole number
</li><li>If you pass the message "do" to an integer with a function as an argument, that function will run as a loop.
</li><li>Functions can have many arguments. You must pass arguments in the correct order or list them by name.
</li><li>Comments are either surrounded by /* and */ or are on a single line, preceded by //
</li><li>All functions return a value, which is the result of the last line of code in the function
</li><li>Variable names are only valid in the block of code in which they were declared, and within blocks of code contained within that block.
</li><li>There are 26 global variables, each a single lowercase letter a-z.
</li></ul>
<h4>Problems</h4>
<ol>
<li>Write a function with nested do-loops, so that there is one loop inside the other.
</li><li>If x and y are intergers and the inner loop is x.do and the outer loop is y.do, how many total times with the inner loop be run?
</li></ol>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com1tag:blogger.com,1999:blog-10668379.post-69013152744967497602010-05-22T17:06:00.006-04:002011-05-16T13:12:16.935-04:00SynthDefs<p><a href="http://sc3howto.blogspot.com/2009/12/variables.html">Last time</a>, I promised we would cover sound-making. First, make sure to boot the localhost server. The localhost server is one of the two small gray boxes at the bottom left of your screen. Press the “Boot” button. When it's booted, the window will say "running" in it and the "Boot" button will turn green and change to say "Quit." <a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhk5nB4aAdvV4MZ_TobU89TIbVMT5TUjBm4DZCMcDe2bYGnVGAQI-6xRgLJjVga51f554Bcw9iAZJdwCs2rd283HebPf83UCm2Xq53xZMBzGQ7LqxaeXvqa753hTmEbkMyvH80UoA/s1600/server.png"><img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 288px; height: 120px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhk5nB4aAdvV4MZ_TobU89TIbVMT5TUjBm4DZCMcDe2bYGnVGAQI-6xRgLJjVga51f554Bcw9iAZJdwCs2rd283HebPf83UCm2Xq53xZMBzGQ7LqxaeXvqa753hTmEbkMyvH80UoA/s400/server.png" border="0" alt="" id="BLOGGER_PHOTO_ID_5474205237097309778" /></a></p>
<p>Then, select this code and press enter (not return!). You can select it by double-clicking to the right of the open parenthesis.</p>
<pre>
(
var syn, sound;
syn = SynthDef.new("example1", {
Out.ar(0, SinOsc.ar(440));
});
syn.load(s);
sound = Synth.new("example1");
)
</pre>
<p>When you want to stop the program, press apple-period.</p>
<p>What's going on here? Our program first declares a variable, and then it defines a SynthDef and loads it on the server, then creates a Synth object that plays the sound. This is a complicated example, but I wanted to get you making sounds as soon as possible. Let's look at the example line by line.</p>
<p>The first line is <span class="s7" style="font: normal normal normal 10px/normal Monaco; ">var syn, sound;</span> We are declaring two variables. One is called syn and the other is called sound.</p>
<p>The next line, translated into English, means "I want to create a new <b>SynthDef</b> called 'example1' and store it in the variable syn." Whoa, what's a SynthDef? The SynthDef help file told me that a SynthDef is a "definition of a synth architecture." I got to the help file by highlighting the word SynthDef and pressing apple-d. When I see a term like that, which I don't understand, I can always get help by highlighting it and typing apple-d.</p>
<p>Recall that SuperCollider is not just one program; it is two. One part of the program is the interpreter, which is what we've been talking about so far. The other part of the program is <b>audio server</b>, which is what actually makes the sound. It does not know anything but what it needs to know. This makes it run much faster and more efficiently. You can tell it to make certain kinds of sounds, but in order to run quickly, it wants to know what kinds of sounds you want before you actually make them. You write a description of what you want the server to do. This description, or definition, is called a SynthDef.</p>
<p>When we run SynthDef.new, we get back a new SynthDef, which we're stroing in the variable named syn. Inside the parenthesis are some <b>arguments</b>. <span class="s13" style="font: normal normal normal 10px/normal Monaco; color: rgb(17, 0, 207); ">SynthDef</span><span class="s14" style="font: normal normal normal 9px/normal Monaco; color: rgb(17, 0, 207); "> </span>is the class.<span class="s3" style="font: normal normal normal 12px/normal Helvetica; "> </span><span class="s7" style="font: normal normal normal 10px/normal Monaco; ">new</span><span class="s3" style="font: normal normal normal 12px/normal Helvetica; "> </span>is the message. And<span class="s3" style="font: normal normal normal 12px/normal Helvetica; "> </span><span class="s7" style="font: normal normal normal 10px/normal Monaco; ">"example1"</span> and the stuff in between the curly brackets are the two arguments. </p>
<p>The stuff in the curly brackets is telling the SynthDef what to play. Things between curly brackets {} are called <b>functions</b>. A function is a special type of object that is made up of a code block that you can run. We'll come back to this later.</p>
<p>Out is a <b>UGen</b>. The help file for UGens says, "A UGen or <b>unit generator </b>is an object for generating or processing audio or control signals." UGens exist in SynthDefs. They are what make up a SynthDef. Out is a UGen that writes a signal to a <b>bus</b>, which, in this case, sends it's output to the left channel. .ar is a type of constructor. So Out.ar creates a new instance of a an Out UGen running at the <b>audio rate</b>. ar stands for "audio rate" and is a common constructor name for UGens. </p>
<p>Looking at the arguments to Out.ar, 0 means left channel. If that were a 1, it would mean right channel. And the next thing is what gets sent out, which is a sine tone generator. The argument to SinOsc.ar, 440, is the frequency to play. So SinOsc.ar(440) creates a sine wave at 440 Hz. Out.ar takes that sine wave and sends it out to the left channel, which is channel 0.</p>
<p>The next line, is a closing curly bracket, a close paren and a semicolon. It's the end of the function, the end of the SynthDef and the end of a statement. We've created a new SynthDef that includes in it a function describing what the SynthDef should do when it gets instantiated.</p>
<p>The next line says, take that SynthDef and load it on the server. We're sending a message to syn, saying load. The argument, s, is the server to send it to. In SuperCollider, a lowercase s by itself refers to the audio server.</p>
<p>The next line asks to create a new Synth. The interpreter sends a message to the server, saying, "Hey, could you make a synth that plays the SynthDef called 'example1'?" The server looks and says, "oh yeah, I have a SynthDef called that" and makes a new instance of a Synth, which is running the function that we defined.</p>
<p>We get a new Synth object back from this and store it in "sound."</p>
<p>Let's say we don't want to play an A. Let's say we want to play an E. We can change 440 to 660.</p>
<pre>
(
var sound;
SynthDef.new("example1a", {
Out.ar(0, SinOsc.ar(660));
}).load(s);
sound = Synth.new("example1a");
)
</pre>
<p>You'll note that we have one fewer variable in that example. Messages are evaluated left to right. So the interpreter first figures out the result of <span class="s13" style="font: normal normal normal 10px/normal Monaco; color: rgb(17, 0, 207); ">SynthDef</span><span class="s7" style="font: normal normal normal 10px/normal Monaco; ">.new(</span><span class="s11" style="font: normal normal normal 10px/normal Monaco; color: rgb(115, 115, 115); ">"example1a"</span><span class="s7" style="font: normal normal normal 10px/normal Monaco; "> ... ). </span>Then, it takes that new SynthDef and sends it the message <span class="s7" style="font: normal normal normal 10px/normal Monaco; ">load. </span> We can keep adding on messages at the end as long as we'd like:</p>
<p><span class="Apple-tab-span" style="white-space: pre; "> </span>object.message1.message2(arg1).message3.message4(arg2)</p>
<p>Of course, this gets silly and difficult to read after a while, but it's legal.</p>
<p>When we're writing a piece, we don't want to have to write a new SynthDef for every note that we're going to play. We can create our own argument, which will tell the SynthDef what frequency to play.</p>
<pre>
(
var sound;
SynthDef.new("example1", { arg freq;
Out.ar(0, SinOsc.ar(freq));
}).load(s);
sound = Synth.new("example1", [\freq, 440]);
)
</pre>
<p >We call that argument “freq.” An argument is a special kind of variable. You declare then at the top of a code block by using the reserved word “arg.” So the <span class="s13" style="font: normal normal normal 10px/normal Monaco; color: rgb(17, 0, 207); ">arg</span><span class="s7" style="font: normal normal normal 10px/normal Monaco; "> freq;</span><span class="s6" style="font: normal normal normal 9px/normal 'Helvetica Neue'; "> </span>part of <span class="s7" style="font: normal normal normal 10px/normal Monaco; ">syn = </span><span class="s13" style="font: normal normal normal 10px/normal Monaco; color: rgb(17, 0, 207); ">SynthDef</span><span class="s7" style="font: normal normal normal 10px/normal Monaco; ">.new(</span><span class="s11" style="font: normal normal normal 10px/normal Monaco; color: rgb(115, 115, 115); ">"example1"</span><span class="s7" style="font: normal normal normal 10px/normal Monaco; ">, { </span><span class="s13" style="font: normal normal normal 10px/normal Monaco; color: rgb(17, 0, 207); ">arg</span><span class="s7" style="font: normal normal normal 10px/normal Monaco; "> freq;</span>tells SuperCollider that our SynthDef function takes a single argument called freq. We can then use freq like we would any other variable. Here, we’re passing to SinOsc.ar, to use for the frequency.</p>
<p>Passing variables to Synths is a bit different than normal variable passing. The interpreter has to communicate with the audio server. They use a protocol called OSC. The Synth object will handle the OSC for you, but the server does not know which argument you’re trying to pass a value to unless you specifically tell it. So Synth.new takes an optional second argument, which is an <b>Array</b>. An array is a list separated by commas and surrounded by square brackets. When you are passing arguments to the server via a synth, the array must be made up of pairs. The first item in a pair is a <b>symbol</b> or a string and the second is a value. The symbol or string must match the name of the argument. So for an argument called freq, we use the symbol \freq or the string “freq”. If we had an argument called amp, we would use the symbol \amp or the string "amp". A symbol starts with a forward slash: ‘\’. So to pass a value of 440 to the argument freq, our array contains [\freq, 440]. If we had two arguments, one freq and the other amp, we could pass values to freq and amp with an array that looks like [\freq, 440, \amp,0.2]. The array is made up of pairs, to the 440 is paired with freq and 0.2 is paired with amp. The symbols or strings must match the names of the arguments taken by the SynthDef function. </p>
<h4>Summary</h4>
<ul>
<li>You must boot the server in order to play sounds.
<li>There is a variable called "s" which always refers to the server
<li>The sounds you want to play must be defined on the server before you play them. They are defined in SynthDefs.
<li>Get help by highlighting a class name with the mouse and typing apple-d
<li>Blocks of code surrounded by curly braces are functions
<li>You play SynthDefs by using Synth
<li>You can declare arguments to a function with the word arg: <span class="s7" style="font: normal normal normal 10px/normal Monaco; ">{ arg agrument1, argument2;</span>
<li>Comma-separated lists surrounded by square brackets are Arrays
<li>Synths use arrays to pass arguments: <span class="s7" style="font: normal normal normal 10px/normal Monaco; ">Synth.new(name, [\symbol, argument])</span>
</ul>
<h4>Problems</h4>
<p>When you are writing code, if you want to syntax colorize it, so that reserved words are blue, strings are grey, symbols are green, and so on, you can find that in the Format menu or just type apple-‘ (apple-single quote).</p>
<ol>
<li>Write your own version of “hello world.”
<li>Write your own SynthDefs, using some of the oscillator UGens. To find a list of them, highlight the word “UGens” and type apple-d. Some oscillators to try are Saw and Pulse.</li>
</ol>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com2tag:blogger.com,1999:blog-10668379.post-71537964159308393092009-12-11T19:46:00.003-05:002010-05-17T14:38:45.861-04:00Variables<p>In previous posts, like, <a href="http://sc3howto.blogspot.com/2005/02/object-oriented-programming.html">Object Oriented Programming</a>, we talked a bit about objects and variables, but in an abstract way. Now, let's get more specific.</p>
<p>A variable is a name for an object. For example, let's think of a person, Nicole, as an object. Now, Nicole, herself is an object, but the word "Nicole" is a name that refers to Nicole the person. Similarly, we can give names to our objects. These names are called <b>variables</b>. Let's see an example:</p>
<p>
<pre>
(
var greeting;
greeting = "hello world";
greeting.postln;
)
</pre>
</p>
<p>To run this code, copy it into a new window in Supercollider and then double click just inside the opening parenthesis to highlight all of it. Then, click the enter key. (Not the return key.) (see also: <a href="http://www.youtube.com/watch?v=Q7OIWcLvmmE">this video</a> for help.) If you look in the Post window, it should say, "hello world."</p>
<p>What's going on there? The first word, "<span style="font-family: courier new;">var</span>," is short for variable. A variable is a storage location. It's a place to store a piece of data. The contents of data stored may vary, which is why it's called a variable. The second word "<span style="font-family: courier new;">greeting</span>" is a name. It is the name of the variables. Here we are <b>declaring</b> to the <b>interpreter</b> that we will have a variable named "<span style="font-family: courier new;">greeting</span>." The interpreter is the part of SuperCollider that reads and runs our programs. So, when the interpreter is reading our program and sees the word "<span style="font-family: courier new;">greeting</span>" it will know that greeting is a variable that we've declared. Otherwise, it wouldn't know what we were talking about.</p>
<p>All variable names in SuperCollider must start with a lowercase letter and cannot be a <b>reserved word</b>. You cannot have a variable called "var" because var already has a special meaning to the interpreter.</p>
<p>Next we are <b>assigning</b> a value to the variable. <span style="font-family: courier new;">greeting</span> gets <span style="font-family: courier new;">"hello world"</span>. The variable is on the left of the equal sign. It must always be on the left. There can only ever be one thing on the left of an equals sign. That sign is saying, 'hey, take whatever is on the right of this equals sign and store it under the variable name on the left.'</p>
<p>In the last line, we're sending a <span style="font-family: courier new;">postln message</span> to the variable. The SuperCollider interpreter sends that <b>message</b> to <span style="font-family: courier new;">greeting</span>. <span style="font-family: courier new;">greeting</span> is a String. Strings print themselves with the postln message. So because <span style="font-family: courier new;">greeting</span> is a
String, the contents of <span style="font-family: courier new;">greeting</span>, <span style="font-family: courier new;">"hello world"</span>, print out. </p>
<p>On the left is the variable name, an object. Then is a period. Then is the name of the message. There are a few different coding styles allowable in SuperCollider, but we're going to focus on receiver notation because it is common across many programming languages. That is:
<pre>
object.message;
</pre></p>
<p>Notice the semi-colons. In Supercollider, all instructions must be separated with a semi-colon. A single instruction can span many lines, so the interpretter needs the semi colon to know when one thing is done and another is starting. Later on, when you're trying to figure out why some program isn't working, you're going to discover a missing semicolon. To be on the safe side, it's good practice to put one at the end of every instruction, as in the example.</p>
<h4>Summary</h4>
<ul>
<li>Variables are named bits of memory which can store objects.</li>
<li>Variables must be declared. Their names must start with lowercase letters</li>
<li>You can assign data to a variable by putting it alone on the left side of an equals sign.</li>
<li>We send messages to objects with the notation <span style="font-family: courier new;">object.message</span></li>
<li>Lines of code must be separated with semicolons</li>
</ul>
<p>The next chapter will make sounds.</p>Charles Céleste Hutchinshttp://www.blogger.com/profile/18123138871494922485noreply@blogger.com0