Product SiteDocumentation Site

11.3.10.8. SynthDef with Arguments

There are some siutations where you simply cannot pre-determine all of the material that you're going to use when creating a synth. It might be easier to resort to using a Function rather than a SynthDef, but there is yet another solution - creating an argument in your SynthDef Function.
With only a subtle change to our Function, we can add the possibility of passing arguments on synth creation:
var myRandFunc =
{
   arg frequency = Rand( 440, 880 ); // default value between 440 and 880
   Out.ar( 0, SinOsc.ar( freq:frequency, mul:0.025 ) );
};
I've decided to use the Rand UGen anyway, so that supplying a frequency is optional. This adds functionality while making the added complexity optional:
(
   var myRandFunc =
   {
      arg frequency = 440;
      Out.ar( 0, SinOsc.ar( freq:frequency, mul:0.025 ) );
   };

   SynthDef.new( \myRandFunc, myRandFunc ).send( s );

   10.do( { Synth.new( \myRandFunc ); } );
)
If you use the SynthDef in the old way, as in the example, you'll get the expected result: ten Synth's, all with the same frequency. But, if you add a "rand" Function call into the loop, you can get ten different frequencies!
(
   var myRandFunc =
   {
      arg frequency = 440;
      Out.ar( 0, SinOsc.ar( freq:frequency, mul:0.025 ) );
   };

   SynthDef.new( \myRandFunc, myRandFunc ).send( s );

   10.do( { Synth.new( \myRandFunc, [\frequency,(440.rand + 440)] ); } );
)
Notice how we supply arguments: an Array with elements alternating between a string-quoted parameter name, and the value of the argument itself. If we "parameterized" all three main fields of the SinOsc, we could supply them like this:
Synth.new( \mySinOsc, [\freq,440,\add,0,\mul,0.2] );