Showing posts with label SuperCollider. Show all posts
Showing posts with label SuperCollider. Show all posts

Saturday, April 25, 2015

How to keep an installation running on a Raspberry Pi

Previously, I covered, how to keep an installation running. In that post, I wrote about how anything could crash. The Pi is much the same, except everything will crash at some point.

I have been working with SC3.6 (see these build instructions), 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

There are a few important differences between running an installation on a laptop and on a Pi.

  • The Pi has fewer resources and crashes much more often and in more ways.
  • The SC server is started separately from sclang
  • 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

Getting the Pi Ready

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 sudo raspi-config. 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.

Getting your code ready

Efficiency

SC 3.6 on a Pi runs exactly the same code as SC 3.6 on my laptop. Therefore, installation-ready code should 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.

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 top -u pi at the command line. The program will tell you the computer's load average and how much of the CPU each program is using.

Within SuperCollider, to find out how much CPU the server is using, Server.default.avgCPU 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.

Starting the server separately

This is a constraint imposed by the build instructions for 3.6. 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 covered in the previous tutorial. The error checking is still useful - even if the server is actually already booted.

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: thisProcess.argv. Arguments to our program start at index 0. We need to get this data before we do anything involving the server.


(
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
)

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.

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.

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.

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.

The Bash scripts

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.

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.

The SuperCollider directory on Pi is either /usr/bin or us/local/bin. to find out which, type which sclang at the command line. If yours is different than the code below, you will need to change it.


#!/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


This script is a lot more complex than the last one! This is because more things can go wrong, alas.

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 killall installation.sh if we don't want the installation to actually run.

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.

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.

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.

We will configure the Pi so the script runs on startup. This means if the computer reboots, the installation will restart.

Then we wait 10 seconds for jack to settle down.

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.

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.

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.

Then, finally, we start running the installation program!

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.

Using helper scripts

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 nice, 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.)

You would alter your script to add:


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

Changing the order

What if you want to start the helper script after 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).


/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

Writing Files

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.

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. (Always make a copy of your SD card!) 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.

Crash Recovery

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.

When my installation is running, I keep my files in /tmp. 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.

Autostart

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.

For Pis that boot to a desktop, you will need to create a file called installation.desktop. Put in it:


[Desktop Entry]
Name=Installation
Exec=/home/pi/installation/installation.sh
Type=application

Change the name and the exec line to match your actual file names and paths. Save that file to ~/.config/autostart/. 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 mv installation.desktop ~/.config/autostart/ . When your computer boots, it will now automatically start your installation when the desktop opens.

Stopping the installation

If you just want to stop everything, shut down the computer! shudo shutdown -h now 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.

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:


killall installation.sh
killall sclang
killall scsynth
killall jackd

To get a list of everything running, use the ps command: ps -u pi . 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: kill 27142. If you notice that your programs are resisting your effort to kill them, you can force them to die: kill -9 27142, where the number is what you see when you run ps.

Debugging

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 'sudo shutdown -r now' lines with 'exit'. 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.

To launch a script form the command line, cd to the directory that its in and type: ./installation.sh . The ./ at the beginning of the command just says that the script is local to the directory that we're in.

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.

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 top -u pi. 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?

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.

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.

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.

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.

the aesthetic of glitch

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.

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.

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.

Conclusion

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.

  • It is still small and cheap, thus making it ideal for installations (and for shipping in the post).
  • It has a certain coolness factor, which may make venues more interested in your work.
  • 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.
  • 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.

Thursday, May 22, 2014

How to keep an installation running

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.

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.

SkipJack

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.

SkipJack({"SkipJack".postln}, 2)

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.

Sclang

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.


var alive, click, dur, task;

dur = 2;
click = { alive = 3 };

task = Task({
inf.do({

"still allive".postln;
click.value;
dur.wait;
})
}).play;

SkipJack({
"are we alive?".postln;
(alive <=0).if({
task.resume;
task.play;
"play!".postln;
(alive <= -2).if({
1.exit;
})
});
alive = alive -1;
}, dur);

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.

The Server

We'll need a separate loop to check on the server.


SkipJack({
Server.default.boot(onFailure:{});
Server.default.doWhenBooted({}, onFailure:{1.exit});

}, dur);

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.

Keeping a Synth Alive

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?


(
var syn, lastrms, max_silence;

SynthDef(\stereoListenForSilence, {|in=0, out=0|
var input;
input = In.ar(in, Server.default.options.numOutputBusChannels);
SendPeakRMS.kr(input, 1, 3, '/loudnessMonitoring'); // send the RMS once per second
ReplaceOut.ar(0, LeakDC.ar(input).tanh); // Optional line to get rid of offset and peaking
}).add;

/* ... */


Synth(\stereoListenForSilence, nil, RootNode(s), \addToTail);

max_silence = 10; // 10 seconds


lastrms=Array.fill(max_silence, {1});

osc_listener = OSCFunc({ |msg|
var rms;
rms = msg[4].asFloat.max(msg[6].asFloat);
lastrms.removeAt(0);
lastrms.add(rms);
(lastrms.sum <= 0.0001).if ({
"too quiet".postln;
// retsart your synths
s.freeAll;
Synth(\myAmazingSynthDef);
Synth(\stereoListenForSilence, nil, RootNode(s), \addToTail);
});
}, '/loudnessMonitoring');


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.

Or if you just want to check if an individual Synth is still running, you can use OSCFuncs and SkipJack together.


(

var syn_alive, dur;

dur =1;
syn_alive = 3;

SynthDef(\myAmazingSynthDef, {

var sin, trig;
SendTrig.kr(Impulse.kr(dur.reciprocal));
sin = SinOsc.ar;
Out.ar(0, sin);

}).add;


/* ... */

Synth(\myAmazingSynthDef);

OSCFunc({ arg msg, time;
syn_alive = 3;
},'/tr', s.addr);


SkipJack({
(syn_alive <=0).if({

s.freeAll;
Synth(\myAmazingSynthDef);

(syn_alive <= -2).if({
1.exit;
})
});
syn_alive = syn_alive -1;
}, dur);


SkipJack({
Server.default.boot(onFailure:{});
Server.default.doWhenBooted({}, onFailure:{1.exit});

}, dur);
)

Try quitting the Server via the gui and everything gets back to where it was in under 3 seconds.

No IDE

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.


#!/bin/bash


while true
do

/path/to/sclang installation.scd

sleep 1

killall scsynth

sleep 1

done


Ok, so first things first, open a terminal and type:

which bash

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.

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'.

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:

chmod +x installation.sh

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.

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.

Helper Apps

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.


#!/bin/bash


while true
do

/path/to/pd hid_helper.pd &
pid=$!
/path/to/sclang installation.scd

sleep 1

killall scsynth
kill $pid

sleep 1

done

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.

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.

Making it all go

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.

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

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.

Wednesday, October 13, 2010

Getting Started with BBCut2

Installing

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

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

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

The Clock

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

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

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

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

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

Working with Buffers

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

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

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

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

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

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

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

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

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

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

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

Cut Procedures

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

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

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

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

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

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

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

  cut.stop;
  cut.free;

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

(
 var clock, sf, cut;
 
 TempoClock.default.tempo_(180/60);
 clock = ExternalClock(TempoClock.default); 
 clock.play;
 
 sf= BBCutBuffer("sounds/break",8);

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

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

  30.wait; //  // let things run for 30 seconds
  
  cut.stop;
  cut.free;
 })
)

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

Polyphony

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

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

You can even mix and match sound files:

(
 var clock, sf1, sf2, cut1, cut2, group;
 
 TempoClock.default.tempo_(180/60);
 clock = ExternalClock(TempoClock.default); 
 clock.play;
 
 sf1= BBCutBuffer("sounds/break",8);
 sf2= BBCutBuffer("sounds/break2",4);

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

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

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

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

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

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

Event.new.play(clock.tempoclock);

Groups and FX

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

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

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

(
var sf, clock;

clock= ExternalClock(TempoClock(2.5)); 
  
clock.play;  
  
Routine.run({
   
sf= BBCutBuffer("sounds/break",8);

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

g=CutGroup(CutBuf1(sf));

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

)

//run these one at a time
g.cutsynths.postln; //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;

Note that the fx that you add on start with index 2.

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

Tying it all Together

Here's an example using everything covered so far:

(
 var clock, sf1, sf2, cut1, cut2, group;
 
 TempoClock.default.tempo_(180/60);
 clock = ExternalClock(TempoClock.default); 
 clock.play;
 
 sf1= BBCutBuffer("sounds/break",8);
 sf2= BBCutBuffer("sounds/break2",4);

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

  group = CutGroup(CutBuf3(sf1, 0.2));  // make a group with a Buffer
  cut1 = BBCut2(group, BBCutProc11(8, 4, 2, 2, 0.2)).play(clock);  // then cut it up
  
  5.wait;
  
  cut2 = BBCut2(CutBuf3(sf2, 0.2),
   BBCutProc11(8, 4, 4, 2, 0.2)).play(clock); // start more drums from the other sound file
  
  5.wait;
  
  group.add(CutComb1.new); // put some FX on the drums in cut1
  
  15.wait;
  
  group.removeAt(2); // take the fx back off
  
  1.wait;
  cut2.pause;
  
  4.wait;
  cut1.stop;
 })
)

Summary

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

Problems

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

More Buffers

Waiting

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

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

s.boot;
 
(
 var buf;
 
 SynthDef(\playBufMono, {| out = 0, bufnum = 0, rate = 1 |
  var scaledRate, player;
  scaledRate = rate * BufRateScale.kr(bufnum);
  player = PlayBuf.ar(1, bufnum, scaledRate, doneAction:2);
  Out.ar(out, player)
 }).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
)

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

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

s.boot;
 
(
 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

)


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

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

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

s.boot;
 
(
 var buf1, syn, pink;
 
 SynthDef(\playBuf1, {| out = 0, bufnum = 0, rate = 1, loop = 1 |
  var scaledRate, player;
  scaledRate = rate * BufRateScale.kr(bufnum);
  player = PlayBuf.ar(1, bufnum, scaledRate, loop: loop,
       doneAction:2);
  Out.ar(out, player)
 }).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
)

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

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

Recording

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

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

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

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

 SynthDef(\recBuf, {| in = 1, bufnum, loop = 1|
 
  var input;
  input = AudioIn.ar(in);
  RecordBuf.ar(input, bufnum, recLevel: 0.7, preLevel: 0.4, loop:loop, doneAction: 2);
 }).add;

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

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

We can mix this with a stuttering playback from earlier:

s.boot;
 
(
 var buf, syn, pb;
 
 SynthDef(\playBuf2, {| out = 0, bufnum = 0, rate = 1, 
       dur = 5, amp = 1, startPos = 0 |
  var scaledRate, player, env;
  
  env = EnvGen.kr(Env.sine(dur, amp), doneAction: 2);
  scaledRate = rate * BufRateScale.kr(bufnum);
  player = PlayBuf.ar(1, bufnum, scaledRate, 
       startPos: startPos, loop:1);
  Out.ar(out, player * env)
 }).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
)

Summary

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

Problems

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

Sunday, October 03, 2010

Working with Buffers

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

 s.boot;
 b = Buffer.read(s, "sounds/a11wlk01.wav");

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

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

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

PlayBuf

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

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

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

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

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

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

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

(
 SynthDef(\playBufMono, {| out = 0, bufnum = 0, rate = 1 |
  var scaledRate, player;
  scaledRate = rate * BufRateScale.kr(bufnum);
  player = PlayBuf.ar(1, bufnum, scaledRate, doneAction:2);
  Out.ar(out, player)
 }).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;
)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Dialogs

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


s.boot;
 
(
 SynthDef(\playBufMono, {| out = 0, bufnum = 0, rate = 1 |
  var scaledRate, player;
  scaledRate = rate * BufRateScale.kr(bufnum);
  player = PlayBuf.ar(1, bufnum, scaledRate, doneAction:2);
  Out.ar(out, player)
 }).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])
  })
 });
)

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

More on Buffers to come!

Summary

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

Tuesday, August 03, 2010

Event

The most important subclass of Dictionary is Event:

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

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

( ).play;

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

Pbind.new.play

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

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

and

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

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

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

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

In your Pbind, you can get access to the current event:

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

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

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

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

(
 Pbind(
  \event, Pfunc({ |evt|
     "Pan before: %".format(evt[\pan]).postln;
    }),
    
  \pan, Pseq([-1], 1),
  
  \event2, Pfunc({ |evt|
     "Pan after: %".format(evt[\pan]).postln;
    })
 ).play
)

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

Let's make the duration depend on the frequency:

(
 Pbind(
  \freq, Prand([440, 550, 660, 770], 10),
  \dur, Pfunc({ |evt|
   
     var dur;
     
     dur = evt[\freq] / 1000
    })
 ).play
)

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

(
 Pbind(
 
  [\freq, \dur],
   Prout({
    var arr, freq, dur;
    
    arr = [440, 550, 660, 770];
    
    10.do({
     
     freq = arr.choose;
     dur = freq / 1000;
     
     [freq, dur].yield;
    })
   })
 ).play
)

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

Summary

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

Friday, June 25, 2010

Dictionary

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

(
 var id;
 
 id = Dictionary.new;
 id.put(\foo, "bar");
 
 id[\foo].postln;
)

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

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

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

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

 keys = id.keys;
 keys.postln;

 keys.do({|key|
  
  "key is %, value is %".format(key, id.at(key)).postln;
 });
)

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

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

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

Here's another example:

(
 var triangle_spectrum, freqs;
 
 triangle_spectrum = Dictionary[
  1->1, 
  3->(1/9), 
  5->(1/25), 
  7->(1/49), 
  9->(1/81)
 ];
 
 freqs = triangle_spectrum.keys;
 freqs = freqs.asArray;
 freqs = freqs.sort;
 
 freqs.do({|freq|
 
  "freq %\t amplitude %\n".postf(freq * 440, triangle_spectrum[freq]);
 })
)

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

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

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

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

(
 var triangle_spectrum, freqs;
 
 triangle_spectrum = Dictionary[
  1->1, 
  3->(1/9), 
  5->(1/25), 
  7->(1/49), 
  9->(1/81)
 ];
 
 freqs = triangle_spectrum.keys;
 freqs = freqs.asArray;
 freqs = freqs.sort({|a, b| a > b});
 
 freqs.do({|freq|
 
  "freq %\t amplitude %\n".postf(freq * 440, triangle_spectrum[freq]);
 })
)

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

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

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

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

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

 id.findKeyForValue(12.5).postln;
)

Summary

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

Thursday, June 24, 2010

Streams

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

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

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

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

(

 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
)

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:

(

 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
)

You can also do math on streams:

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

And you can do binary math operations on two streams:

(
 var stream1, stream2, sum;

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

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

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

(
 var notes, pbind;
 
 notes = Pseq([ 1/1, 3/2, 4/3, 9/8, 16/9, 5/4, 8/5 ].pyramid(1), 2).asStream;
 notes = notes * 440;
 
 pbind = { |dur = 0.5|
 
  Pbind(
   \dur, dur,
   \freq, Pfunc({notes.next})
  )
 };
 
 Ppar([pbind.value(0.5), pbind.value(0.751)]).play;
)

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

Summary

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

Tuesday, June 08, 2010

Math with Patterns & Prout

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

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

What if you want to square your random numbers?

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

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

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

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

(
 var num;
 num = 5;
 
 Pbind(
  \dur,  0.2,
  \note, Pwhite(0, 5) * Pfunc({num})
 ).play;
 
 Task({
  5.wait;
  num = 2;
 }).play;
)

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

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

Or Pshuf does the same thing:

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

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

(
 var arr, rout;
 
 arr = [1, 3, 5, 7];
 
 rout = Prout({ 
  5.do({
   arr.scramble.do({|item|
    item.yield;
  })})
 });

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

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

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

(
 var arr, rout;
 
 arr = [1, 3, 5, 7];
 
 rout = Prout({ 
  10.do({
   arr.scramble.do({|item|
    item.yield;
  })})
 });

 
 Pbind(
  \dur, 0.2,
  \note, rout
 ).play;
 
 Task({
  2.wait;
  arr = [12, 15, 19, 21];
  2.wait;
  arr = [-12, -13, -11];
 }).play
)

You could do something similar also, this way:

(
 var arr1, arr2, arr3, rout;
 
 arr1 = [1, 3, 5, 7];
 arr2 = [12, 15, 19, 21];
 arr3 = [-12, -13, -11];
 
 rout = Prout({ 
  3.do({
   arr1.scramble.do({|item|
    item.yield;
  })});
  3.do({
   arr2.scramble.do({|item|
    item.yield;
  })});
  3.do({
   arr3.scramble.do({|item|
    item.yield;
  })})
 });

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

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

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

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

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

And, as with Pfunc, you can do math:

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

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

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

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

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

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

Summary

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

Sunday, June 06, 2010

Pfunc

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

(
 var db, pbind, task;
 
 db = -12;
 
 task = Task({
 
  // ...
  
  5.wait;
  
  60.do({
  
   db = db - 1;
   0.1.wait;
  });
  
  "done fading".postln;
 });
 
 // ...
)

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

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

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

Now for the pbind:

 // ...

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

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

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

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

 // ...
 
 pbind.play;
 task.play;

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

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

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

 // ...

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

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

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

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

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

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

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

The final version of this example, all together is:

(
 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;
 
)

Summary

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

Problem

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

Saturday, June 05, 2010

Polyphony and Sequencing

Chords

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

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

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

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

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

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

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

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

Pbind(\midinote, 60.05).play

60.05 is middle C, 5 cents sharp.

Rests

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

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

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

Ppar

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

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

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

a and b play exactly in time with each other.

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

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

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

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

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

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

Summary

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

Problems

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

Friday, June 04, 2010

Pbinds

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

p = Pbind.new.play;

That will repeat forever until you stop it.

p.stop;

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

Pbind(\freq, 660).play

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

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

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

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

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

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

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

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

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

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

You can also play through a list with Pseq:

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

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

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

The lists passed to patterns can contain other patterns:

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

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

(
 SynthDef(\example9, {|out = 0, freq, amp, dur, pan = 0, mod = 50|
  
  var pm, modulator, env, panner;
  
  modulator = SinOsc.ar(mod, 0, 0.2);
  pm = SinOsc.ar(freq, modulator);
  
  env = EnvGen.kr(Env.perc(0.01, dur, amp), doneAction:2);
  panner = Pan2.ar(pm, pan, env);
  
  Out.ar(out, panner);
 }).store
)

Then, specify it:

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

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

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

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

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

(
 SynthDef(\example9a, {|out = 0, freq, amp, dur, pan = 0, mod = 50, modulation_depth = 0.2|
  
  var pm, modulator, env, panner;
  
  modulator = SinOsc.ar(mod, 0, modulation_depth);
  pm = SinOsc.ar(freq, modulator);
  
  env = EnvGen.kr(Env.perc(0.01, dur, amp), doneAction:2);
  panner = Pan2.ar(pm, pan, env);
  
  Out.ar(out, panner);
 }).store
)


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

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

Summary

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

Monday, May 31, 2010

Arrays

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

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

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

a = Array.new(size);

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

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

Arrays can even hold other arrays:

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

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

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

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

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

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

 " ".postln;

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

Outputs:

[ 2 ]
2

[ 2 ]
3
3

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

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

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

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

Outputs:

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

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

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

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

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

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

For me, this output:

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

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

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

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

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

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

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

Outputs:

had
little

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

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

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

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

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

Outputs:

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

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

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

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

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

(
 var arr1, arr2, arr3;
 
 arr1 = [1, 2, 3];
 arr2 = arr1 ++ 4;
 arr3 = arr2 ++ [5, 6];
 
 arr1.postln;
 arr2.postln;
 arr3.postln;
)

Outputs

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

Note that the receiver is unchanged.

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

arr.at(index % arr.size);

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

arr.wrapAt(index);

It does the modulus for you.

Musical Example

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

She's created SynthDef:

(
 SynthDef(\example8, {|out = 0, freq, amp, dur, pan = 0|
  
  var pm, modulator, env, panner;
  
  modulator = SinOsc.ar(50, 0, 0.2);
  pm = SinOsc.ar(freq, modulator);
  
  env = EnvGen.kr(Env.perc(0.01, dur, amp), doneAction:2);
  panner = Pan2.ar(pm, pan, env);
  
  Out.ar(out, panner);
 }).store
)

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

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

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

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

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

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

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

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

She writes her code as follows:


(

  var func, arr;
  
  func = { |ratio_arr, baseFreq = 440, detune = 10, dur  = 0.2|
   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;
)

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

Summary

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

Problems

  1. You can navigate arrays of different length using variables for indexes.
  2. (
    
     var arr1, arr2, index;
    
     arr1 = [1, 2, 3];
     arr2 = [3, 4, 5, 6];
     index = 0;
    
     2.do({
      arr1.do({ arg item;
       ("arr1 " ++ item).postln;
       ("\t arr2 " ++ arr2.wrapAt(index)).postln; //"\t" means tab 
       index = index + 1;
      });
     });
    )
    
    Use this idea to create duration, pitch and wait loops of different lengths. Write a task to pay them
  3. In the previous post, there was an example that used if statements to control adding to or subtracting from the frequency. Instead of changing the frequency directly, change an index that will access an array of tuning ratios.