/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / instruments / effects.ts
62 lines · 2.0 KBCodeBlameHistory
75ca48aOverhaul playback: background-computed, buffered, one clockJeremy Magland 1// Effects after the rendered audio, on the page (native Web Audio nodes: cheap and steady):
2// a sound's own modal-synth effects, or dry plus a send to one reverb shared by several outputs.
4import { FX } from "@modal-synth/audio/fx.ts";
5import type { Params } from "@modal-synth/engine/params.ts";
7export function routeEffects(ctx: AudioContext, from: AudioNode, out: AudioNode, sound: Params | undefined, effects: "own" | "none" | { send: AudioNode }) {
8 if (!sound) {
9 from.connect(out);
10 return;
11 }
12 if (effects === "own") {
13 const fx = new FX(ctx, out);
14 from.connect(fx.input);
15 fx.set(sound);
16 return;
17 }
18 const vol = ctx.createGain();
19 vol.gain.value = Math.pow(10, (sound.volume as number) / 20);
20 from.connect(vol).connect(out);
21 if (effects !== "none") {
22 const send = ctx.createGain();
23 send.gain.value = (sound.reverbMix as number) * vol.gain.value;
24 from.connect(send).connect(effects.send);
25 }
28/** One convolution reverb shared by several outputs (decaying noise whose tail darkens). */
29export class SharedReverb {
30 input: GainNode;
31 private conv: ConvolverNode;
33 constructor(ctx: AudioContext, out: AudioNode, T60: number) {
34 this.input = ctx.createGain();
35 this.conv = ctx.createConvolver();
36 this.conv.buffer = makeIR(ctx, T60);
37 this.input.connect(this.conv).connect(out);
38 }
40 dispose() {
41 this.input.disconnect();
42 this.conv.disconnect();
43 }
46function makeIR(ctx: BaseAudioContext, T60: number): AudioBuffer {
47 const sr = ctx.sampleRate;
48 const n = Math.round(sr * Math.min(T60 * 1.1, 12));
49 const buf = ctx.createBuffer(2, n, sr);
50 for (let ch = 0; ch < 2; ch++) {
51 const d = buf.getChannelData(ch);
52 let lp = 0;
53 for (let i = 0; i < n; i++) {
54 const t = i / sr;
55 const fc = 9000 * Math.exp(-t / (0.6 * T60)) + 400;
56 const a = 1 - Math.exp((-2 * Math.PI * fc) / sr);
57 lp += a * (Math.random() * 2 - 1 - lp);
58 d[i] = lp * Math.exp((-6.9 * t) / T60) * Math.min(1, t / 0.004) * 0.5;
59 }
60 }
61 return buf;
↑↓ move↵openescclose