#13 Advanced Envelopes

Create and use an envelope manually. You can create an envelope object using the create method on the envelope definition.

Note that you have to sample the value property every frame to make sure the envelope is correctly updated.

dittytoy.net/syntax#envelopes

#dittytoy #tutorial

Log in to post a comment.

// #13 Advanced Envelopes. DittyToy 2022.
// The MIT License.
//
// https://dittytoy.net/ditty/d0b9a59b10
//
// Create and use an envelope manually. You can create an envelope object using the create method on the envelope definition.
//
// Note that you have to sample the value property every frame to make sure the envelope is correctly updated.
//
// adsr      envelope: https://dittytoy.net/ditty/34e1600f63
// adsr2     envelope: https://dittytoy.net/ditty/0f2e4c2cdd
// segmented envelope: https://dittytoy.net/ditty/ce63852ccf
//
// https://dittytoy.net/syntax#envelopes
//

const osc = synth.def( 
    class {
            constructor(options) {
                this.phase = 0;
                this.hist0 = 0;
                this.hist1 = 0;
                
                // Create an adsr envelope for the low pass filter
                // Attack, decay and release in seconds. Duration in ticks. 
                this.lowPassEnv = adsr.create({attack: 0.05, decay: 0.15, sustain: .25, release: 0.1, duration: options.duration});
            }
            process(note, env, tick, options) {
                this.phase += midi_to_hz(note) * ditty.dt;
                
                let ret = this.phase % 1 - .5;

                // low pass filter, cutoff is based on lowPass envelope
                const alpha = clamp01(this.lowPassEnv.value * .5 ** 2);
                this.hist0 += alpha * (ret - this.hist0);
                this.hist1 += alpha * (this.hist0 - this.hist1);
                
                return this.hist1;
            }
    }, { attack: 0.01, release: 0.1, duration: 0.25 } );


loop( () => {
    for (let i=0; i<4; i++) {
        osc.play(c4, { attack: 0.01, release: 0.25,  duration: 0.125, amp: 1.0 });
        sleep( 0.25 );
    }

    osc.play(d4, { attack: 0.01, release: 0.25,  duration: 0.25 }); // attack and release in seconds, duration in ticks
    sleep(0.5); // sleep in ticks

    osc.play(f4, { attack: 0.01, release: 0.75,  duration: 0.25 });
    sleep(0.5);
}, { name: 'Advanced Envelopes' });