#07 Envelopes

Define your own envelope using env.def, by setting a class that implements a duration and a value method.

Based on gist.github.com/samaaron/3f41f913bf6d1b6bf036 by @samaaron

dittytoy.net/syntax#envelopes

#dittytoy #tutorial

Log in to post a comment.

// #07 Envelopes. DittyToy 2022.
// The MIT License.
//
// https://dittytoy.net/ditty/24fb0f9063
//
// Define your own envelope using env.def, by setting a class that implements a duration and a value method.
// 
// https://dittytoy.net/syntax#envelopes
//

// Create a sin-envelope

const sinenv = env.def(
    class {
        duration(options) { // duration in ticks
            return options.duration; 
        }
        value(tick, options) {
            return .5 - .5 * Math.cos(tick / options.duration * 2 * Math.PI);
        }
    }, 
    { duration: 1, name: 'sinenv' }
);

// You can set the envelope type using the env option (both in the default options of a synth, and when you play a note)
const tri = synth.def( (phase, env) => { const v = (phase % 1) * 4; return (v < 2 ? v - 1 : 3 - v) * env.value }, { duration: 0.5, env: sinenv, amp: .75 });

ditty.bpm = 130;

loop( () => {
    sine.play(d3, { attack: 0.025, release: 24, amp: (tick) => .75 + .5 * Math.sin(tick * Math.PI * 4), env: adsr2 });

    for (let i=0; i<6; i++) {
        [d, 0, 0, a, f5, 0, a, 0].forEach( note => {
            if(note) tri.play(note, { pan: Math.random() * 2 - 1 });
            sleep(.25);
        });
    }

    sine.play(g3, { attack: 0.025, release: 8, amp: (tick) => .75 + .5 * Math.sin(tick * Math.PI * 4), env: adsr2 });

    for (let i=0; i<2; i++) {
        [d, 0, 0, Bb, g5, 0, Bb, 0].forEach( note => {
            if(note) tri.play(note, { pan: Math.random() * 2 - 1 });
            sleep(.25);
        });
    }
}, { name: 'melody' });