Last active
January 12, 2018 14:03
-
-
Save bnolan/120c755d29702a7ec76befaa762ec3d8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
float lerp(float a, float b, float f) | |
{ | |
return a + f * (b - a); | |
} | |
class Envelope { | |
public: | |
float attack, decay, sustain, release, start; | |
int period; | |
// attack, decay and release are in millis | |
// sustain is an amplitude (float of 0-1) | |
Envelope (float a, float d, float s, float r) { | |
start = millis(); | |
attack = a; | |
decay = d; | |
sustain = s; | |
release = r; | |
} | |
// You have to specify how long the period is (the time from | |
// noteOn to noteOff) in millis | |
void trigger (int p) { | |
start = millis(); | |
period = p; | |
} | |
float value () { | |
int t = millis() - start; | |
if (t < attack) { | |
return lerp (0, 1, 1.0 / attack * t); | |
} else if (t < attack + decay) { | |
return lerp (1, sustain, 1.0 / decay * (t - attack)); | |
} else if (t < period - release) { | |
return sustain; | |
} else if (t < period) { | |
return lerp (sustain, 0, 1.0 / release * (t - period + release )); | |
} else { | |
return 0; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment