/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / instruments / glide.ts
62 lines · 2.3 KBCodeBlameHistory
f7d91baAdd composition 4: crashJeremy Magland 1// A soft, gliding tone whose pitch can follow something continuously (like a theremin): a sine
2// with a quiet octave triangle, gently low-passed, with a slow vibrato. Cheap, smooth, and
3// unobtrusive.
5export class GlideVoice {
6 private out: GainNode;
7 private oscs: OscillatorNode[];
8 private filter: BiquadFilterNode;
9 private lfo: OscillatorNode;
10 private lfoGain: GainNode;
11 private ctx: AudioContext;
13 constructor(ctx: AudioContext, dest: AudioNode) {
14 this.ctx = ctx;
15 this.out = ctx.createGain();
16 this.out.gain.value = 0;
17 this.filter = ctx.createBiquadFilter();
18 this.filter.type = "lowpass";
19 this.filter.Q.value = 0.5;
20 this.filter.connect(this.out).connect(dest);
21 const sine = ctx.createOscillator();
22 const tri = ctx.createOscillator();
23 tri.type = "triangle";
24 const triGain = ctx.createGain();
25 triGain.gain.value = 0.12;
26 sine.connect(this.filter);
27 tri.connect(triGain).connect(this.filter);
28 this.oscs = [sine, tri];
29 // vibrato (in cents, on both oscillators)
30 this.lfo = ctx.createOscillator();
31 this.lfo.frequency.value = 4.8;
32 this.lfoGain = ctx.createGain();
33 this.lfoGain.gain.value = 6;
34 this.lfo.connect(this.lfoGain);
35 for (const o of this.oscs) this.lfoGain.connect(o.detune);
36 }
38 start(when: number, freq: number) {
39 this.set(when, freq, 0, 0.3, 6);
40 for (const o of [...this.oscs, this.lfo]) o.start(when);
41 }
43 /** freq (Hz), level (linear), brightness 0..1 (filter), vibrato depth in cents */
44 set(when: number, freq: number, level: number, brightness: number, vibrato: number) {
45 const tc = 0.03;
46 this.oscs[0].frequency.setTargetAtTime(freq, when, tc);
47 this.oscs[1].frequency.setTargetAtTime(2 * freq, when, tc);
48 this.filter.frequency.setTargetAtTime(freq * (1.5 + 6 * Math.max(0, Math.min(1, brightness))), when, tc);
49 this.out.gain.setTargetAtTime(level, when, 0.08);
50 this.lfoGain.gain.setTargetAtTime(vibrato, when, 0.2);
51 }
53 stop(when: number, release: number) {
54 this.out.gain.cancelScheduledValues(this.ctx.currentTime);
55 this.out.gain.setTargetAtTime(0, Math.max(this.ctx.currentTime, when - release), release / 4);
56 for (const o of [...this.oscs, this.lfo]) o.stop(when + 0.1);
57 }
59 dispose() {
60 window.setTimeout(() => this.out.disconnect(), 1500);
61 }
↑↓ move↵openescclose