2 summary:: Client-side representation of a synth definition
3 categories:: Server>Abstractions
4 related:: Classes/Synth, Reference/Synth-Definition-File-Format, Classes/SynthDesc
8 The server application uses synth definitions as templates for creating link::Classes/Synth:: nodes.
9 (Methods such as link::Classes/Function#play#Function-play::, etc. are simply conveniences which automatically create such a def.)
10 The SynthDef class encapsulates the client-side representation of a given def, and provides methods for creating new defs, writing them to disk, and streaming them to a server.
12 SynthDef is one of the more complicated classes in SC and an exhaustive explanation of it is beyond the scope of this document. As such, the examples at the bottom of this document and those found in the various tutorials accessible from link::Help:: may be necessary to make some aspects of its use clear.
14 subsection:: UGen Graph Functions and Special Argument Forms
16 The core of a def is its link::Classes/UGen##unit generator:: graph function.
17 This is an instance of link::Classes/Function:: which details how the def's unit generators are interconnected, its inputs and outputs, and what parameters are available for external control.
18 In a synth based on the def, arguments to the function will become instances of link::Classes/Control::.
19 These can have default values, or can be set at the time the synth is created.
20 After creation they will be controllable through link::Classes/Node::'s code::set:: and code::setn:: methods, or the n_set and n_setn link::Browse#OpenSoundControl#OSC:: messages.
22 There are four special types of arguments, which are treated differently:
25 || Arguments that begin with "a_" (e.g. code::a_input::), or that are specified as code::\ar:: in the def's rates argument (see below), will be able to read and audio rate bus when mapped to it with code::/n_mapa::.
27 || Arguments that begin with "i_" (e.g. code::i_freq::), or that are specified as code::\ir:: in the def's rates argument (see below), will be static and non-modulatable. They will not respond to code::/n_set:: or code::/n_map::. This is slightly more efficient in terms of CPU than a regular arg.
29 || Arguments that begin with "t_" (e.g. code::t_trig::), or that are specified as code::\tr:: in the def's rates argument (see below), will be made as a link::Classes/TrigControl::. Setting the argument will create a control-rate impulse at the set value. This is useful for triggers.
31 || Arguments which have literal arrays as default values (see link::Reference/Literals::) result in multichannel controls, which can be set as a group with link::Classes/Node#setn#Node-setn:: or code::/n_setn::. When setting such controls no bounds checking is done, so you are responsible for making sure that you set the correct number of arguments.
34 See the examples below for more detail on how this works.
36 Certain argument names (such as 'out' to specify an out bus) are in such common use that adopting them might be said to constitute 'good style'.
37 One of these, 'gate' when used to control the gate input of an link::Classes/EnvGen::, deserves special mention, as it allows one to use Node's release method. See link::Classes/Node:: for an example and more detail.
39 subsection:: Static versus Dynamic Elements
41 It is important to understand that although a single def can provide a great deal of flexibility through its arguments, etc., it is nevertheless a static entity.
42 A def's link::Classes/UGen:: graph function (and the SC code within it) is evaluated only when the def is created.
43 Thus statements like while, do, collect etc. will have no further effect at the time the def is used to create a Synth, and it is important to understand that a UGen graph function should not be designed in the same way as functions in the language, where multiple evaluations can yield different results. It will be evaluated once and only once.
44 note:: code::if:: is implemented as a linear signal crossfade when the receiver is an UGen ::
46 There are other ways of achieving similar results, however, often using UGens such as Rand. For example, the following def will have a single randomly generated frequency, which will be the same for every Synth based on it:
49 SynthDef(\help_notRand, {
51 SinOsc.ar(rrand(400, 800), 0, 0.2) * Line.kr(1, 0, 1, doneAction: 2)
55 a = Synth(\help_notRand);
56 b = Synth(\help_notRand); // the same freq as a
58 This one on the other hand will have a different random freq for each Synth created:
61 SynthDef(\help_isRand, {
63 SinOsc.ar(Rand(400, 800), 0, 0.2) * Line.kr(1, 0, 1, doneAction: 2)
67 a = Synth(\help_isRand);
68 b = Synth(\help_isRand); // a different randomly selected freq
73 private:: initClass, prNew
76 Create a SynthDef instance, evaluate the ugenGraphFunc and build the ugenGraph.
78 A link::Classes/String:: or link::Classes/Symbol:: (i.e. "name" or \name). This name will be used to refer to the SynthDef when creating a Synth based upon it, and should be unique.
79 argument:: ugenGraphFunc
80 An instance of Function specifying how the def's UGens are interconnected. See the discussion above for information on how the Function's arguments are specified.
82 An optional Array of specifications for the ugenGraphFunc's arguments. The order corresponds to the order of arguments. See the examples below to see how these are used.
84 A specification can be:
86 ## nil/zero || A standard control rate link::Classes/Control:: is created.
87 ## \ar || An audio rate link::Classes/AudioControl:: is created.
88 ## a float || the Control will have a lag of the specified time. This can be used to create
89 smooth transitions between different values. t_ and i_ args cannot be lagged.
90 ## \ir || The Control can be set only at creation ('initial rate'). See discussion above.
91 ## \tr || The Control is used as a trigger. See discussion above.
94 argument:: prependArgs
95 An optional link::Classes/Array:: of objects which will be passed as the first arguments to the ugenGraphFunc when it is evaluated. Arguments which receive values in this way will not be converted to instances of link::Classes/Control::. See the code::wrap:: example below for an example of how this can be used.
98 An optional link::Classes/Event:: containing default argument settings. These can override the defaults specified in the ugenGraphFunc. When creating a Synth a variant can be requested by appending the defName argument in the form 'name.variant' or "name.variant". See example below.
101 An optional link::Classes/Event:: containing additional, user-defined information that is relevant to the use of the SynthDef in the client. The SynthDef itself is sent to the server for audio rendering; metadata are strictly client-side descriptive information. Currently the 'specs' key in the event is reserved for link::Classes/ControlSpec::s to be associated with SynthDef arguments (this is useful for automatic GUI construction). Metadata can be persisted to disk and loaded automatically as part of a SynthDesc. See the link::Classes/SynthDesc:: help file for more details.
105 Wraps a function within an enclosing synthdef.
107 Arguments to the wrapped function are automatically promoted to be SynthDef controls, using the same rules applied to arguments of the main UGen function. For a very simple example:
109 d = SynthDef(\demoWrapping, { |out|
110 Out.ar(out, SynthDef.wrap({ |freq| SinOsc.ar(freq) }))
115 Prints: code:: [ ControlName P 0 out control 0, ControlName P 1 freq control 0 ] ::.
117 The outer function declares the argument 'out', and the wrapped function has 'freq' as its argument. The resulting SynthDef has both arguments as controls, exactly as if the outer function included both as arguments.
119 The rates array behaves as described earlier. code::PrependArgs:: allows values or unit generators to be passed into the inner function from the enclosing SynthDef context. Any inner function argument that receives a prependArg value (including nil) will use that value, suppressing creation of a control for that argument. The longer example below demonstrates this technique.
121 This is very useful for mass-producing SynthDefs that have a common "shell" defining features such as enveloping or triggering mechanisms that apply to different subgraphs of unit generators. The common features need be written only once; the UGens that differ between the SynthDefs are plugged into the supporting architecture.
124 Get or set the default directory to which defs are written.
127 Remove the synthdef code::name:: from the SynthDescLib named code::libname:: and from its servers.
130 Create a new SynthDef and write it to disk, but only if a def file with this name does not already exist. This is useful in class definitions so that the def is not written every time the library is compiled. Note that this will not check for differences, so you will need to delete the defFile to get it to rebuild. Default for dir is to use the path specified by code::SynthDef.synthDefDir::.
136 Adds the synthdef to the link::Classes/SynthDescLib:: specified by libname, and sends it to the library's servers. No defFile is written; all operations take place in memory.
139 After using this method, the synthdef can be used with event streams as in code::store()::, but without the permanent artifact of a file on disk.
141 A server can be added by code:: SynthDescLib.global.addServer(server) ::.
143 Note that the "dir" and "mdPlugin" arguments do not exist for this method. Because no file is written, there is no need to specify a directory or write a metadata file.
147 SynthDef(\help_synth, { |out, freq = 800, sustain = 1, amp = 0.1|
149 SinOsc.ar(freq, 0, 0.2) * Line.kr(amp, 0, sustain, doneAction: 2)
156 Return this def's name.
159 Return this def's ugenGraphFunc.
162 Return an Event containing this def's variants.
164 method:: allControlNames
165 An array of link::Classes/ControlName::'s for the controls.
167 subsection:: Special purpose methods
168 (for most purposes, the method add is recommended)
170 method:: writeDefFile
171 Writes the def as a file called name.scsyndef in a form readable by a server. Default for dir is synthdefs/. Defs stored in the default directory will be automatically loaded by the local and internal Servers when they are booted.
174 Write the defFile and send a message to server to load this file. When this asynchronous command is completed, the completionMessage (a valid OSC message) is immediately executed by the server. Default for dir is synthdefs/.
177 Compile the def and send it to server without writing to disk (thus avoiding that annoying SynthDef buildup). When this asynchronous command is completed, the completionMessage (a valid OSC message) is immediately executed by the server.
180 Write the defFile and store it in the SynthDescLib specified by libname, and send a message to the library's server to load this file. When this asynchronous command is completed, the completionMessage (a valid OSC message) is immediately executed by the server. Default for libname is \global, for dir is synthdefs/. This is needed to use defs with the event stream system. See Streams and Pattern.
183 (optional) The metadata plug-in class that will be used to persist metadata. If not supplied, the default plug-in is used. See the SynthDesc help file for details.
187 This method has been deprecated, use add instead.
190 A convenience method which compiles the def and sends it to target's server. When this asynchronous command is completed, it create one synth from this definition, using the argument values specified in the Array args. For a list of valid addActions see link::Classes/Synth::. The default is \addToHead.
191 Returns:: a corresponding Synth object.
198 // Note that constructions like SynthDef(...) and Synth(...) are short for SynthDef.new(...), etc.
199 // With SynthDef it is common to chain this with calls on the resulting instance,
200 // e.g. SynthDef(...).add or SynthDef(...).play
202 // make a simple def and send it to the server
205 SynthDef(\SimpleSine, {|freq = 440| Out.ar(0, SinOsc.ar(freq, 0, 0.2)) }).add;
207 // the above is essentially the same as the following:
208 d = SynthDef.new(\SimpleSine, {|freq = 440| Out.ar(0, SinOsc.ar(freq, 0, 0.2)) });
211 // now make a synth from it, using the default value for freq, then another with a different value
212 x = Synth(\SimpleSine);
213 y = Synth(\SimpleSine, [\freq, 660]);
215 // now change the freq value for x
220 // using the play convenience method
221 x = SynthDef(\SimpleSine, {|freq = 440| Out.ar(0, SinOsc.ar(freq, 0, 0.2)) }).play
225 subsection:: Argument Rates
227 // the following two defs are equivalent. The first uses a 't_' arg:
229 SynthDef(\trigTest, {|t_trig=0, freq=440| // t_trig creates a TrigControl
230 Out.ar(0, SinOsc.ar(freq+[0,1], 0, Decay2.kr(t_trig, 0.005, 1.0)));
231 }, [0, 4] // lag the freq by 4 seconds (the second arg), but not t_trig (won't work anyway)
235 // This second version makes trig a \tr arg by specifying it in the rates array.
237 SynthDef(\trigTest2, {|trig=0, freq=440|
238 Out.ar(0, SinOsc.ar(freq+[0,1], 0, Decay2.kr(trig, 0.005, 1.0)));
239 }, [\tr, 4] // lag the freq (lagtime: 4s), \tr creates a TrigControl for trig
243 // Different way of writing the same thing
245 SynthDef(\trigTest2, {
246 Out.ar(0, SinOsc.ar(\freq.kr(440, 4) + [0,1], 0, Decay2.kr(\trig.tr, 0.005, 1.0)));
251 // Using the second version create a synth
252 z = Synth.head(s, \trigTest2);
254 // now trigger the decay envelope
255 z.set(\trig, 1); // you can do this multiple times
256 z.set(\trig, 1, \freq, 220); // hear how the freq lags
257 z.set(\trig, 1, \freq, 880);
259 z.free; //free the synth
262 subsection:: Variants
264 // create a def with some variants
266 SynthDef(\vartest, {|out=0, freq=440, amp=0.2, a = 0.01, r = 1|
267 // the EnvGen with doneAction: 2 frees the synth automatically when done
268 Out.ar(out, SinOsc.ar(freq, 0, EnvGen.kr(Env.perc(a, r, amp), doneAction: 2)));
269 }, variants: (alpha: [a: 0.5, r: 0.5], beta: [a: 3, r: 0.01], gamma: [a: 0.01, r: 4])
273 // now make some synths. First using the arg defaults
276 // now the variant defaults
277 Synth('vartest.alpha');
278 Synth('vartest.beta');
279 Synth('vartest.gamma');
281 // override a variant
282 Synth('vartest.alpha', [\release, 3, \freq, 660]);
285 subsection:: Literal Array Arguments
287 // freqs has a literal array of defaults. This makes a multichannel Control of the same size.
289 SynthDef(\arrayarg, { | amp = 0.1, freqs = #[300, 400, 500, 600], gate = 1 |
291 env = Linen.kr(gate, 0.1, 1, 1, 2) * amp;
292 sines = SinOsc.ar(freqs +.t [0,0.5]).cubed.sum; // A mix of 4 oscillators
293 Out.ar(0, sines * env);
297 x = Synth(\arrayarg);
298 x.setn(\freqs, [440, 441, 442, 443]);
300 // Don't accidentally set too many values, or you may have unexpected side effects
301 // The code below inadvertantly sets the gate arg, and frees the synth
302 x.setn(\freqs, [300, 400, 500, 600, 0]);
304 // Mr. McCartney's more complex example
307 z = Synth(\arrayarg);
311 z.setn(\freqs, {exprand(200,800.0)} ! 4);
312 (2 ** (0..3).choose * 0.2).wait;
315 z.set(\amp, -40.dbamp);
318 z.setn(\freqs, {exprand(200,800.0)} ! 4);
319 (2 ** (0..3).choose * 0.2).wait;
328 subsection:: Wrapping Example: 'factory' production of effects defs
330 // The makeEffect function below wraps a simpler function within itself and provides
331 // a crossfade into the effect (so you can add it without clicks), control over wet
333 // Such functionality is useful for a variety of effects, and SynthDef-wrap
334 // lets you reuse the common code.
337 ~makeEffect = {| name, func, lags, numChannels = 2 |
339 SynthDef(name, {| i_bus = 0, gate = 1, wet = 1|
340 var in, out, env, lfo;
341 in = In.ar(i_bus, numChannels);
342 env = Linen.kr(gate, 2, 1, 2, 2); // fade in the effect
344 // call the wrapped function. The in and env arguments are passed to the function
345 // as the first two arguments (prependArgs).
346 // Any other arguments of the wrapped function will be Controls.
347 out = SynthDef.wrap(func, lags, [in, env]);
349 XOut.ar(i_bus, wet * env, out);
350 }, [0, 0, 0.1] ).add;
357 ~makeEffect.value(\wah, {|in, env, rate = 0.7, ffreq = 1200, depth = 0.8, rq = 0.1|
358 // in and env come from the wrapper. The rest are controls
360 lfo = LFNoise1.kr(rate, depth * ffreq, ffreq);
361 RLPF.ar(in, lfo, rq, 10).distort * 0.15; },
362 [0.1, 0.1, 0.1, 0.1], // lags for rate ffreq, depth and rq
367 // now make a simple reverb
369 ~makeEffect.value(\reverb, {|in, env|
370 // in and env come from the wrapper.
373 16.do({ input = AllpassC.ar(input, 0.04, Rand(0.001,0.04), 3)});
380 // something to process
381 x = { {Decay2.ar(Dust2.ar(3), mul: PinkNoise.ar(0.2))} ! 2}.play;
383 y = Synth.tail(s, \wah);
384 z = Synth.tail(s, \reverb, [\wet, 0.5]);
386 // we used an arg named gate, so Node-release can crossfade out the effects
389 // setting gate to zero has the same result
395 subsection:: common argument names: out and gate
397 // arguments named 'out' and 'gate' are commonly used to specify an output bus and
398 // EnvGen gate respectively. Although not required, using them can help with consistency
399 // and interchangeability. 'gate' is particularly useful, as it allows for Node's release
402 SynthDef(\synthDefTest, {|out, gate=1, freq=440|
403 // doneAction: 2 frees the synth when EnvGen is done
404 Out.ar(out, SinOsc.ar(freq) * EnvGen.kr(Env.asr(0.1, 0.3, 1.3), gate, doneAction:2));
405 }).store; // use store for compatibility with pattern example below
408 x = Synth(\synthDefTest, [\out, 0]); // play out through hardware output bus 0 (see Out.help)
409 x.release; // releases and frees the synth (if doneAction is > 2; see EnvGen)
413 x = Synth(\synthDefTest); // out defaults to zero, if no default arg is given.
416 // if value is negative, it overrides the release time, to -1 - gate
417 x = Synth(\synthDefTest);
418 x.set(\gate, -5); // 4 second release
421 x = Synth(\synthDefTest);
424 // if the out arg is used in a standard way, it can always be changed without knowing the synth def
425 x = Synth(\synthDefTest, [\out, 0]);
426 x.set(\out, 1); //play through channel 1
429 // Another good example of this is with patterns, which can use gate to release notes
432 \instrument, \synthDefTest,
433 \freq, Pseq([500, 600, Prand([200, 456, 345],1)], inf),
434 \legato, Pseq([1.5, 0.2], inf),
436 \out, Pseq([0, 1], inf)