| 1 |
// name: adsr.ck |
| 2 |
// desc: an ADSR envelope describes how a sound changes over time. |
| 3 |
// It's often used in music synthesis to control the volume of |
| 4 |
// a sound. ADSR stands for Attack, Decay, Sustain, and Release. |
| 5 |
// Each of these terms describes a different part of the sound's |
| 6 |
// volume over time. In this example, an ADSR is used to shape |
| 7 |
// a continuous sine wave into individual notes. |
| 8 |
// |
| 9 |
// /\ |
| 10 |
// / \_____ |
| 11 |
// / \ |
| 12 |
// The general shape of a ADSR envelope. |
| 13 |
// |
| 14 |
// (A)ttack: This is the initial burst of sound when a note is |
| 15 |
// played. It's how quickly the volume reaches its maximum level. |
| 16 |
// |
| 17 |
// (D)ecay: After the attack, the sound level will decrease over |
| 18 |
// time to a lower level. The decay time is how long it takes for |
| 19 |
// the sound to reach the sustain level. |
| 20 |
// |
| 21 |
// (S)ustain: This is the steady state of the sound after the |
| 22 |
// initial attack and decay. The sound remains at a constant level |
| 23 |
// as long as the note is held down. |
| 24 |
// |
| 25 |
// (R)elease: When the note is released, the sound level will drop |
| 26 |
// back down to zero. The release time is how long it takes for the |
| 27 |
// sound to fade away completely. |
| 28 |
// |
| 29 |
// for more info on envelopes and ADSRs see: |
| 30 |
// https://en.wikipedia.org/wiki/Envelope_(music)#ADSR |
| 31 |
|
| 32 |
// our patch |
| 33 |
SinOsc s => ADSR e => dac; |
| 34 |
|
| 35 |
// set A, D, S, and R |
| 36 |
e.set( 10::ms, 8::ms, .5, 500::ms ); |
| 37 |
// (note: A, D, R are durations; S is a number between 0 and 1) |
| 38 |
|
| 39 |
// set gain |
| 40 |
.5 => s.gain; |
| 41 |
|
| 42 |
// infinite time-loop |
| 43 |
while( true ) |
| 44 |
{ |
| 45 |
// choose freq |
| 46 |
Math.random2( 32, 96 ) => Std.mtof => s.freq; |
| 47 |
|
| 48 |
// key on: begin ATTACK |
| 49 |
// (note: ATTACK automatically transitions to DECAY; |
| 50 |
// DECAY automatically transitions to SUSTAIN) |
| 51 |
e.keyOn(); |
| 52 |
// advance time by 500 ms |
| 53 |
// (note: this is the duration from the |
| 54 |
// beginning of ATTACK to the end of SUSTAIN) |
| 55 |
500::ms => now; |
| 56 |
// key off; start RELEASE |
| 57 |
e.keyOff(); |
| 58 |
// allow the RELEASE to ramp down to 0 |
| 59 |
e.releaseTime() => now; |
| 60 |
|
| 61 |
// advance time by 300 ms (duration until the next sound) |
| 62 |
300::ms => now; |
| 63 |
} |