Wednesday 1 February 2012

My First SynthDef

I just spent some time learning about SynthDef's, or Synth Definitions. Writing some code and executing it with .play; or .scope; is all well and good, but for a practical application not so much. My professor Nick Collins, who has some awesome Supercollider tutorials here (http://www.informatics.sussex.ac.uk/users/nc81/courses/cm1/sccourse.zip), describes a SynthDef as the recipe for a synth - once we have the recipe, we can use it many times, create multiple instances of the same Synth, and then manipulate those instances.

Here's the first, simplest SynthDef from the tutorials:

SynthDef(\sine, {Out.ar(0,SinOsc.ar(Rand(440,880),0,0.1))}).add;

This defines a synth (named \sine) that outputs a sine wave, that will take a random frequency value from between 440 and 880 each time it is instantiated. This randomisation is caused by using the Rand function for the frequency parameter of the SinOsc.

Once you execute that code and add (".add;") the SynthDef to the server, you can execute is thusly

Synth(\sine);

Much nicer than writing

{SinOsc.ar(440,0,0,1)}.play;

over and over.

Listening to a constant sine tone can get pretty boring though. I was pleased to discover that we can easily make things more interesting by adding arguments to the SynthDef - like frequency and amplitude arguments, for example.

SynthDef(\sine2,{arg freq = 220, amp = 0.5;
Out.ar(0,SinOsc.ar(freq,0,amp))}).add;
         
h=Synth(\sine2);
i=Synth(\sine2,[\freq,550]);
j=Synth(\sine2,[\freq,660, \amp,0.5]);

I'm really starting to appreciate the way things can plug into each other easily in Supercollider. Here, I initialise (you have to set default values) the arguments of frequency and amplitude at 220Hz and 0.5*. Then, we pass these arguments to the frequency and amplitude parameters of the SinOsc that produces the output. We can then instantiate them one at a time, with different frequency arguments each time. The sound gets richer as you add more.

Here's an example of me running the same SynthDef over and over, setting a different frequency argument each time.

http://soundcloud.com/samlovett/harmonic-synthdefs
Once you stop the SynthDef, use the code h.free; to stop the synth running.

Towards the end of the tutorial, there was an exercise to turn a patch you'd previously worked on into a SynthDef - so I did exactly that. Here's the square wave modulator we looked at before, turned into a SynthDef.


My First Synth Def

SynthDef(\squaremod, {Out.ar(0,
        {
            var modfreq, modindex;
           
            modfreq=MouseX.kr(1,440,'exponential');
            modindex=MouseY.kr(0.0,15,0);
           
            LFPulse.ar(
                SinOscFB.ar(modfreq,1,modfreq*modindex,120),0,0.5)*0.1
        })}).add;
       
Synth(\squaremod);

The fact that I can utilise all of that code (perhaps "all of" isn't quite right) just by typing Synth(\squaremod); makes me very happy.