/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / instruments / reverb.ts
42 lines · 1.3 KBBlameHistoryRaw
1// One convolution reverb shared by several instruments (instead of one per instrument, which is
2// costly on phones). The impulse response is the same kind modal-synth's effects use: decaying
3// noise whose tail darkens over time.
5export class SharedReverb {
6 /** send instruments' wet signal here */
7 input: GainNode;
8 private conv: ConvolverNode;
10 constructor(ctx: AudioContext, out: AudioNode, T60: number) {
11 this.input = ctx.createGain();
12 this.conv = ctx.createConvolver();
13 this.conv.buffer = makeIR(ctx, T60);
14 this.input.connect(this.conv).connect(out);
15 }
17 dispose() {
18 const i = this.input, c = this.conv;
19 window.setTimeout(() => {
20 i.disconnect();
21 c.disconnect();
22 }, 1500);
23 }
26function makeIR(ctx: BaseAudioContext, T60: number): AudioBuffer {
27 const sr = ctx.sampleRate;
28 const n = Math.round(sr * Math.min(T60 * 1.1, 12));
29 const buf = ctx.createBuffer(2, n, sr);
30 for (let ch = 0; ch < 2; ch++) {
31 const d = buf.getChannelData(ch);
32 let lp = 0;
33 for (let i = 0; i < n; i++) {
34 const t = i / sr;
35 const fc = 9000 * Math.exp(-t / (0.6 * T60)) + 400;
36 const a = 1 - Math.exp((-2 * Math.PI * fc) / sr);
37 lp += a * (Math.random() * 2 - 1 - lp);
38 d[i] = lp * Math.exp((-6.9 * t) / T60) * Math.min(1, t / 0.004) * 0.5;
39 }
40 }
41 return buf;
↑↓ move↵openescclose