To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.
root / CollidoscopeApp / include / EnvASR.h @ 2:dd889fff8423
History | View | Annotate | Download (1.96 KB)
| 1 | 0:02467299402e | f | #pragma once
|
|---|---|---|---|
| 2 | |||
| 3 | namespace collidoscope {
|
||
| 4 | |||
| 5 | 2:dd889fff8423 | f | |
| 6 | /*
|
||
| 7 | * An ASR envelope with linear shape. It is modeled after the STK envelope classes.
|
||
| 8 | * The tick() method advances the computation of the envelope one sample and returns the computed sample
|
||
| 9 | * The class is templated for the type of the samples that each tick of the envelope produces.
|
||
| 10 | *
|
||
| 11 | * Client classes can set/get the current state of the envelope with the
|
||
| 12 | * respective getter/setter methods
|
||
| 13 | *
|
||
| 14 | */
|
||
| 15 | 0:02467299402e | f | template <typename T> |
| 16 | class EnvASR |
||
| 17 | {
|
||
| 18 | public:
|
||
| 19 | |||
| 20 | enum class State {
|
||
| 21 | eAttack, |
||
| 22 | eSustain, |
||
| 23 | eRelease, |
||
| 24 | eIdle // before attack after release
|
||
| 25 | }; |
||
| 26 | |||
| 27 | EnvASR( T sustainLevel, T attackTime, T releaseTime, std::size_t sampleRate ) : |
||
| 28 | mSustainLevel( sustainLevel ), |
||
| 29 | mState( State::eIdle ), |
||
| 30 | mValue( 0 )
|
||
| 31 | |||
| 32 | {
|
||
| 33 | if ( attackTime <= 0 ) |
||
| 34 | attackTime = T( 0.001 ); |
||
| 35 | |||
| 36 | if ( releaseTime <= 0 ) |
||
| 37 | releaseTime = T( 0.001 ); |
||
| 38 | |||
| 39 | mAttackRate = T( 1.0 ) / (attackTime * sampleRate); |
||
| 40 | mReleaseRate = T( 1.0 ) / (releaseTime * sampleRate); |
||
| 41 | } |
||
| 42 | |||
| 43 | T tick() |
||
| 44 | {
|
||
| 45 | |||
| 46 | switch ( mState )
|
||
| 47 | {
|
||
| 48 | |||
| 49 | case State::eIdle: {
|
||
| 50 | mValue = 0;
|
||
| 51 | }; |
||
| 52 | break;
|
||
| 53 | |||
| 54 | case State::eAttack: {
|
||
| 55 | mValue += mAttackRate; |
||
| 56 | if ( mValue >= mSustainLevel ){
|
||
| 57 | mValue = mSustainLevel; |
||
| 58 | mState = State::eSustain; |
||
| 59 | } |
||
| 60 | }; |
||
| 61 | break;
|
||
| 62 | |||
| 63 | case State::eRelease:
|
||
| 64 | mValue -= mReleaseRate; |
||
| 65 | if ( mValue <= 0 ){ |
||
| 66 | mValue = 0;
|
||
| 67 | mState = State::eIdle; |
||
| 68 | } |
||
| 69 | break;
|
||
| 70 | default:
|
||
| 71 | break;
|
||
| 72 | } |
||
| 73 | |||
| 74 | return mValue;
|
||
| 75 | |||
| 76 | } |
||
| 77 | |||
| 78 | State getState() const
|
||
| 79 | {
|
||
| 80 | return mState;
|
||
| 81 | } |
||
| 82 | |||
| 83 | void setState( State state )
|
||
| 84 | {
|
||
| 85 | mState = state; |
||
| 86 | } |
||
| 87 | |||
| 88 | private:
|
||
| 89 | T mSustainLevel; |
||
| 90 | T mAttackRate; |
||
| 91 | T mReleaseRate; |
||
| 92 | |||
| 93 | // output
|
||
| 94 | T mValue; |
||
| 95 | |||
| 96 | State mState; |
||
| 97 | |||
| 98 | }; |
||
| 99 | |||
| 100 | |||
| 101 | 2:dd889fff8423 | f | } |