oneShot: free the responder before running user func (avoid error)
[supercollider.git] / HelpSource / Classes / SynthDef.schelp
blob03648acfc5b6f2f37d2048de02261df9e5965873
1 class:: SynthDef
2 summary:: Client-side representation of a synth definition
3 categories:: Server>Abstractions
4 related:: Classes/Synth, Reference/Synth-Definition-File-Format
6 description::
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:
23 definitionlist::
24 ## audio rate
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::.
26 ## initial rate
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.
28 ## trigger rate
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.
30 ## literal arrays
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:
47 code::
49 SynthDef(\help_notRand, { 
50         Out.ar(0, 
51                 SinOsc.ar(rrand(400, 800), 0, 0.2) * Line.kr(1, 0, 1, doneAction: 2)
52         )
53 }).add;
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:
59 code::
61 SynthDef(\help_isRand, { 
62         Out.ar(0, 
63                 SinOsc.ar(Rand(400, 800), 0, 0.2) * Line.kr(1, 0, 1, doneAction: 2)
64         ) 
65 }).add;
67 a = Synth(\help_isRand);
68 b = Synth(\help_isRand); // a different randomly selected freq
72 ClassMethods::
73 private:: initClass, prNew
75 method:: new
76 Create a SynthDef instance, evaluate the ugenGraphFunc and build the ugenGraph.
77 argument:: name
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.
81 argument:: rates
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:
85 definitionlist::
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.
96         
97 argument:: variants
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.
100 argument:: metadata
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.
104 method:: wrap
105 Wraps a function within an enclosing synthdef.
106 discussion::
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:
108 code::
109 d = SynthDef(\demoWrapping, { |out|
110         Out.ar(out, SynthDef.wrap({ |freq| SinOsc.ar(freq) }))
113 d.allControlNames;
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.
123 method:: synthDefDir
124 Get or set the default directory to which defs are written.
126 method:: removeAt
127 Remove the synthdef code::name:: from the SynthDescLib named code::libname:: and from its servers.
129 method:: writeOnce
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::.
133 InstanceMethods::
135 method:: add
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.
138 discussion::
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.
145 code::
147 SynthDef(\help_synth, { |out, freq = 800, sustain = 1, amp = 0.1|
148         Out.ar(out, 
149                 SinOsc.ar(freq, 0, 0.2) * Line.kr(amp, 0, sustain, doneAction: 2)
150         ) 
151 }).add;
155 method:: name
156 Return this def's name.
157         
158 method:: func
159 Return this def's ugenGraphFunc.
160         
161 method:: variants
162 Return an Event containing this def's variants.
164         
165 subsection:: Special purpose methods
166 (for most purposes, the method add is recommended)
167         
168 method:: writeDefFile
169 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.
170                 
171 method:: load
172 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/.
173                 
174 method:: send
175 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.
177 method:: store
178 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.
179         
180 argument:: mdPlugin
181 (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.
184 method:: memStore
185 This method has been deprecated, use add instead.
187 method:: play
188 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.
189 Returns:: a corresponding Synth object.
190         
192 Examples::
194 subsection:: Basic
195 code::
196 // Note that constructions like SynthDef(...) and Synth(...) are short for SynthDef.new(...), etc.
197 // With SynthDef it is common to chain this with calls on the resulting instance,
198 // e.g. SynthDef(...).add or SynthDef(...).play
200 // make a simple def and send it to the server
202 s.boot;
203 SynthDef(\SimpleSine, {|freq = 440| Out.ar(0, SinOsc.ar(freq, 0, 0.2)) }).add;
205 // the above is essentially the same as the following:
206 d = SynthDef.new(\SimpleSine, {|freq = 440| Out.ar(0, SinOsc.ar(freq, 0, 0.2)) });
207 d.add;
209 // now make a synth from it, using the default value for freq, then another with a different value
210 x = Synth(\SimpleSine);
211 y = Synth(\SimpleSine, [\freq, 660]);
213 // now change the freq value for x
214 x.set(\freq, 880);
216 x.free; y.free;
218 // using the play convenience method
219 x = SynthDef(\SimpleSine, {|freq = 440| Out.ar(0, SinOsc.ar(freq, 0, 0.2)) }).play
220 x.free;
223 subsection:: Argument Rates
224 code::
225 // the following two defs are equivalent. The first uses a 't_' arg:
227 SynthDef(\trigTest, {|t_trig=0, freq=440| // t_trig creates a TrigControl
228         Out.ar(0, SinOsc.ar(freq+[0,1], 0, Decay2.kr(t_trig, 0.005, 1.0)));
229 }, [0, 4]               // lag the freq by 4 seconds (the second arg), but not t_trig (won't work anyway)
233 // This second version makes trig a \tr arg by specifying it in the rates array.
235 SynthDef(\trigTest2, {|trig=0, freq=440| 
236         Out.ar(0, SinOsc.ar(freq+[0,1], 0, Decay2.kr(trig, 0.005, 1.0)));
237         }, [\tr, 4]             // lag the freq (lagtime: 4s), \tr creates a TrigControl for trig
238 ).add;          
241 // Different way of writing the same thing
243 SynthDef(\trigTest2, {
244         Out.ar(0, SinOsc.ar(\freq.kr(440, 4) + [0,1], 0, Decay2.kr(\trig.tr, 0.005, 1.0)));
245 }).add;                 
249 // Using the second version create a synth
250 z = Synth.head(s, \trigTest2);
252 // now trigger the decay envelope
253 z.set(\trig, 1);                                // you can do this multiple times 
254 z.set(\trig, 1, \freq, 220);    // hear how the freq lags
255 z.set(\trig, 1, \freq, 880);
257 z.free; //free the synth
260 subsection:: Variants
261 code::
262 // create a def with some variants
264 SynthDef(\vartest, {|out=0, freq=440, amp=0.2, a = 0.01, r = 1|
265         // the EnvGen with doneAction: 2 frees the synth automatically when done
266         Out.ar(out, SinOsc.ar(freq, 0, EnvGen.kr(Env.perc(a, r, amp), doneAction: 2)));
267 }, variants: (alpha: [a: 0.5, r: 0.5], beta: [a: 3, r: 0.01], gamma: [a: 0.01, r: 4])
268 ).add;
271 // now make some synths. First using the arg defaults
272 Synth(\vartest);
274 // now the variant defaults
275 Synth('vartest.alpha');
276 Synth('vartest.beta');
277 Synth('vartest.gamma');
279 // override a variant
280 Synth('vartest.alpha', [\release, 3, \freq, 660]);
283 subsection:: Literal Array Arguments
284 code::
285 // freqs has a literal array of defaults. This makes a multichannel Control of the same size.
287 SynthDef(\arrayarg, { | amp = 0.1, freqs = #[300, 400, 500, 600], gate = 1 |
288         var env, sines;
289         env = Linen.kr(gate, 0.1, 1, 1, 2) * amp;
290         sines = SinOsc.ar(freqs +.t [0,0.5]).cubed.sum; // A mix of 4 oscillators
291         Out.ar(0, sines * env); 
292 }, [0, 0.1, 0]).add;
295 x = Synth(\arrayarg);
296 x.setn(\freqs, [440, 441, 442, 443]);
298 // Don't accidentally set too many values, or you may have unexpected side effects
299 // The code below inadvertantly sets the gate arg, and frees the synth
300 x.setn(\freqs, [300, 400, 500, 600, 0]);
302 // Mr. McCartney's more complex example
304 fork {  
305         z = Synth(\arrayarg);
306         
307         2.wait;
308         10.do {
309                 z.setn(\freqs, {exprand(200,800.0)} ! 4);
310                 (2 ** (0..3).choose * 0.2).wait;
311         };
313         z.set(\amp, -40.dbamp);
315         10.do {
316                 z.setn(\freqs, {exprand(200,800.0)} ! 4);
317                 (2 ** (0..3).choose * 0.2).wait;
318         };
319         2.wait;
320         
321         z.release;
326 subsection:: Wrapping Example: 'factory' production of effects defs
327 code::
328 // The makeEffect function below wraps a simpler function within itself and provides
329 // a crossfade into the effect (so you can add it without clicks), control over wet
330 // and dry mix, etc.
331 // Such functionality is useful for a variety of effects, and SynthDef-wrap
332 // lets you reuse the common code.
334 // the basic wrapper
335 ~makeEffect = {| name, func, lags, numChannels = 2 |
337         SynthDef(name, {| i_bus = 0, gate = 1, wet = 1|
338                 var in, out, env, lfo;
339                 in = In.ar(i_bus, numChannels);
340                 env = Linen.kr(gate, 2, 1, 2, 2); // fade in the effect
341                 
342                 // call the wrapped function. The in and env arguments are passed to the function
343                 // as the first two arguments (prependArgs). 
344                 // Any other arguments of the wrapped function will be Controls.
345                 out = SynthDef.wrap(func, lags, [in, env]);
346                 
347                 XOut.ar(i_bus, wet * env, out);
348         }, [0, 0, 0.1] ).add;
353 // now make a wah
355 ~makeEffect.value(\wah, {|in, env, rate = 0.7, ffreq = 1200, depth = 0.8, rq = 0.1|
356         // in and env come from the wrapper. The rest are controls
357         var lfo;
358         lfo = LFNoise1.kr(rate, depth * ffreq, ffreq);
359         RLPF.ar(in, lfo, rq, 10).distort * 0.15; },
360         [0.1, 0.1, 0.1, 0.1],  // lags for rate ffreq, depth and rq
361         2       // numChannels
365 // now make a simple reverb
367 ~makeEffect.value(\reverb, {|in, env|
368         // in and env come from the wrapper.
369         var input;
370         input = in;
371         16.do({ input = AllpassC.ar(input, 0.04, Rand(0.001,0.04), 3)});
372         input; },
373         nil,  // no lags
374         2       // numChannels
378 // something to process
379 x = { {Decay2.ar(Dust2.ar(3), mul: PinkNoise.ar(0.2))} ! 2}.play;
381 y = Synth.tail(s, \wah);
382 z = Synth.tail(s, \reverb, [\wet, 0.5]);
384 // we used an arg named gate, so Node-release can crossfade out the effects
385 y.release; 
387 // setting gate to zero has the same result
388 z.set(\gate, 0);
390 x.free;
393 subsection:: common argument names: out and gate
394 code::
395 // arguments named 'out' and 'gate' are commonly used to specify an output bus and
396 // EnvGen gate respectively. Although not required, using them can help with consistency
397 // and interchangeability. 'gate' is particularly useful, as it allows for Node's release
398 // method.
400 SynthDef(\synthDefTest, {|out, gate=1, freq=440|
401         // doneAction: 2 frees the synth when EnvGen is done
402         Out.ar(out, SinOsc.ar(freq) * EnvGen.kr(Env.asr(0.1, 0.3, 1.3), gate, doneAction:2));
403 }).store; // use store for compatibility with pattern example below
406 x = Synth(\synthDefTest, [\out, 0]); // play out through hardware output bus 0 (see Out.help)
407 x.release; // releases and frees the synth (if doneAction is > 2; see EnvGen)
409 //equivalent:
411 x = Synth(\synthDefTest); // out defaults to zero, if no default arg is given.
412 x.set(\gate, 0);
414 // if value is negative, it overrides the release time, to -1 - gate
415 x = Synth(\synthDefTest);
416 x.set(\gate, -5); // 4 second release
418 //equivalent:
419 x = Synth(\synthDefTest);
420 x.release(4);
422 // if the out arg is used in a standard way, it can always be changed without knowing the synth def
423 x = Synth(\synthDefTest, [\out, 0]);
424 x.set(\out, 1); //play through channel 1
425 x.release;
427 // Another good example of this is with patterns, which can use gate to release notes
429 Pbind(
430         \instrument, \synthDefTest,
431         \freq, Pseq([500, 600, Prand([200, 456, 345],1)], inf),
432         \legato, Pseq([1.5, 0.2], inf),
433         \dur, 0.4,
434         \out, Pseq([0, 1], inf)
435 ).play;