To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Tag: | Revision:

root / CollidoscopeApp / include / EnvASR.h @ 3:7fb593d53361

History | View | Annotate | Download (2.08 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 3:7fb593d53361 f
    /** Possible states of the envelope. Idle means the envelope ouputs 0 */
21 0:02467299402e f
    enum class State {
22
        eAttack,
23
        eSustain,
24
        eRelease,
25
        eIdle // before attack after release
26
    };
27
28
    EnvASR( T sustainLevel, T attackTime, T releaseTime, std::size_t sampleRate ) :
29
        mSustainLevel( sustainLevel ),
30
        mState( State::eIdle ),
31
        mValue( 0 )
32
33
    {
34
        if ( attackTime <= 0 )
35
            attackTime = T( 0.001 );
36
37
        if ( releaseTime <= 0 )
38
            releaseTime = T( 0.001 );
39
40
        mAttackRate =  T( 1.0 ) / (attackTime * sampleRate);
41
        mReleaseRate = T( 1.0 ) / (releaseTime * sampleRate);
42
    }
43
44 3:7fb593d53361 f
    /** Produces one sample worth of envelope */
45 0:02467299402e f
    T tick()
46
    {
47
48
        switch ( mState )
49
        {
50
51
        case State::eIdle: {
52
            mValue = 0;
53
        };
54
            break;
55
56
        case State::eAttack: {
57
            mValue += mAttackRate;
58
            if ( mValue >= mSustainLevel ){
59
                mValue = mSustainLevel;
60
                mState = State::eSustain;
61
            }
62
        };
63
            break;
64
65
        case State::eRelease:
66
            mValue -= mReleaseRate;
67
            if ( mValue <= 0 ){
68
                mValue = 0;
69
                mState = State::eIdle;
70
            }
71
            break;
72
        default:
73
            break;
74
        }
75
76
        return mValue;
77
78
    }
79
80
    State getState() const
81
    {
82
        return mState;
83
    }
84
85
    void setState( State state )
86
    {
87
        mState = state;
88
    }
89
90
private:
91
    T mSustainLevel;
92
    T mAttackRate;
93
    T mReleaseRate;
94
95
    // output
96
    T mValue;
97
98
    State mState;
99
100
};
101
102
103 2:dd889fff8423 f
}