// Example 4a- linear and exponential envelopes


// Creating a custom envelope using a linear shape.

// Over attdur seconds, rise to attamp,

// over decdur seconds, move to decamp,

// over susdur seconds, move to susamp,

// then release to 0 over ireldur.

// Duration of the sustain (susdur) is derived from the other

// durations to complete the duration of the note.

// This is often called an ADSR (attack-decay-sustain-release) envelope

(

var noteObject, note;

noteObject = CtkSynthDef(\example4a, {arg dur = 1, freq = 440, attdur = 0.1, 

attamp = -3, decdur = 0.07, decayamp = -6, susamp = -9, reldur = 0.3;

var susdur, env, sound, envgen;

// calculate the sustain portion

susdur = dur - (attdur + decdur + reldur); 

//levels (converted to amps)

env = Env([0, attamp.dbamp, decayamp.dbamp, susamp.dbamp, 0], 

[attdur, decdur, susdur, reldur], //times

\lin); //shape

sound = SinOsc.ar(freq, 0, 1);

envgen = EnvGen.kr(env);

Out.ar(0, sound * envgen);

});


note = noteObject.new(0.0, 1.0); // a sample note, using all the defualt arguments

note.play;

)



// This time, the shape of the envelope uses exponential curves.

// Notice that level values may never be 0, or cross 0!


(

var noteObject, note;

noteObject = CtkSynthDef(\example4b, {arg dur = 1, freq = 440, attdur = 0.1, 

attamp = -3, decdur = 0.07, decayamp = -6, susamp = -9, reldur = 0.3;

var susdur, env, sound, envgen;

// calculate the sustain portion

susdur = dur - (attdur + decdur + reldur); 

// this time, all the values in the Env are in db ...

env = Env([-90, attamp, decayamp, susamp, -90], //levels

[attdur, decdur, susdur, reldur], //times

\exp); //shape

sound = SinOsc.ar(freq, 0, 1);

// ... then we can convert from db to linear amp here

envgen = EnvGen.ar(env).dbamp;

Out.ar(0, sound * envgen);

});

note = noteObject.new(0.0, 1.0);

note.play;

)