/ interactive_tutorials / duffing_islands
Sign in
interactive_tutorials / duffing_islands
duffing_islands / app / js / voices.js
308 lines · 12.8 KBBlameHistoryRaw
1// The instruments the orbits play, and the mapping from a point's x to its
2// pitch. Each orbit plays its own voice, so several can be told apart.
3//
4// Each note is rendered once into an AudioBuffer (cached per voice, pitch
5// and sustain), given a soft attack and a short fade at the end, and matched
6// in loudness to all the others. Every voice and pitch rings for the same
7// time: the sustain, the time for the fundamental to fade by 60 dB (set by
8// the page). So the voices differ in timbre and attack, not in how long
9// they ring, and loudness is matched by the RMS over each note's onset (its
10// first LOUD_WINDOW s) after the K-weighting filter of ITU-R BS.1770 (a high
11// shelf of +4 dB above about 1.7 kHz, where the ear is most sensitive, and a
12// high-pass at 38 Hz): the same for every voice, pitch and sustain.
13// - Strings (harp, pizzicato) are Karplus-Strong: the string starts in a
14// rounded, fingertip-plucked shape and circulates in a delay line of one
15// period, through a gentle low-pass (so the high harmonics die away first,
16// leaving a warm tone) and a first-order all-pass that tunes the
17// fractional part of the period.
18// - Bars, tines and the ocarina are modal: a few decaying sinusoids, at the
19// instrument's partial ratios (marimba 1 : 3.93 : 9.2, vibraphone
20// 1 : 4 : 10 with tremolo, and so on).
21// - The electric piano is two-operator FM with a fading modulation index.
22// Everything goes through a soft low-pass, a dark synthetic reverb and a
23// limiter.
25export const DEFAULT_SCALE = 'Minor pentatonic';
26export const KEYS = ['C', 'C♯', 'D', 'E♭', 'E', 'F', 'F♯', 'G', 'A♭', 'A', 'B♭', 'B'];
27export const DEFAULT_KEY = 9; // A
29// Scales as semitone offsets within an octave; null: continuous pitch.
30export const SCALES = [
31 { name: 'Major pentatonic', steps: [0, 2, 4, 7, 9] },
32 { name: 'Minor pentatonic', steps: [0, 3, 5, 7, 10] },
33 { name: 'Major', steps: [0, 2, 4, 5, 7, 9, 11] },
34 { name: 'Natural minor', steps: [0, 2, 3, 5, 7, 8, 10] },
35 { name: 'Harmonic minor', steps: [0, 2, 3, 5, 7, 8, 11] },
36 { name: 'Whole tone', steps: [0, 2, 4, 6, 8, 10] },
37 { name: 'Chromatic', steps: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] },
38 { name: 'Continuous', steps: null },
39];
41const LOW = 130.81; // C3, the pitch at the left edge of the view
42const OCTAVES = 3; // up to C6 at the right edge
44// The pitch (Hz) for u in [0, 1] (the left to right edge of the view): the
45// notes of the scale in the given key (0 = C, ..., 11 = B) that lie within
46// OCTAVES octaves from LOW, spread evenly across the view; or continuous.
47// The register stays put when the key changes, so a key change shifts the
48// harmony, like a chord change.
49export function pitchOf(u, scale, key = 0) {
50 u = Math.min(1, Math.max(0, u));
51 if (!scale.steps) return LOW * 2 ** (OCTAVES * u);
52 const notes = [];
53 for (let s = 0; s <= 12 * OCTAVES; s++) {
54 if (scale.steps.includes((((s - key) % 12) + 12) % 12)) notes.push(s);
55 }
56 return LOW * 2 ** (notes[Math.round(u * (notes.length - 1))] / 12);
59export const SUSTAIN = { min: 0.1, max: 4, step: 0.1, default: 2 }; // s
60const LOUD_WINDOW = 0.3; // s
61const LOUDNESS = 0.12; // target K-weighted RMS over LOUD_WINDOW
63// Karplus-Strong string: t60 (s, for the fundamental to fade by 60 dB),
64// pluck (where along the string it is plucked: smaller is brighter).
65function string(sr, freq, t60, { pluck = 0.15 } = {}) {
66 const len = Math.ceil(sr * t60);
67 const out = new Float32Array(len);
68 // Loop delay L = sr / freq: N samples, plus one for the [1/4, 1/2, 1/4]
69 // loop filter, plus the all-pass's d (kept in [0.5, 1.5), where it is
70 // accurate and well behaved).
71 const L = sr / freq;
72 const N = Math.floor(L - 1.5);
73 const d = L - 1 - N;
74 const c = (1 - d) / (1 + d);
75 // the loop filter takes cos^2(pi f / sr) off each harmonic per pass, so
76 // the highs die away within a few periods; the loop gain makes up the
77 // fundamental's share, so it still fades over t60
78 const H1 = Math.cos((Math.PI * freq) / sr) ** 2;
79 const g = Math.min(0.99995, 10 ** (-3 / (t60 * freq)) / H1);
80 // the pluck: the string's initial shape, a triangle peaked at `pluck` of
81 // its length (harmonics falling as 1/k^2: at 0.15, about -8, -14, -21 dB
82 // for the 2nd to 4th), its corner rounded off as by a fingertip, with a
83 // trace of noise
84 const tri = new Float32Array(N);
85 for (let i = 0; i < N; i++) {
86 const u = (i + 0.5) / N;
87 tri[i] = u < pluck ? u / pluck : (1 - u) / (1 - pluck);
88 }
89 const w = Math.max(1, Math.round(N / 25));
90 const line = new Float32Array(N);
91 for (let i = 0; i < N; i++) {
92 let acc = 0;
93 for (let k = -w; k <= w; k++) acc += tri[(i + k + N) % N];
94 line[i] = acc / (2 * w + 1);
95 }
96 let mean = 0;
97 for (let i = 0; i < N; i++) { line[i] += 0.02 * (Math.random() * 2 - 1); mean += line[i] / N; }
98 for (let i = 0; i < N; i++) line[i] -= mean;
99 let pos = 0;
100 let y1 = 0;
101 let y2 = 0;
102 let apIn = 0;
103 let apOut = 0;
104 for (let n = 0; n < len; n++) {
105 const y = line[pos];
106 const lp = 0.25 * y + 0.5 * y1 + 0.25 * y2;
107 y2 = y1;
108 y1 = y;
109 const ap = c * lp + apIn - c * apOut;
110 apIn = lp;
111 apOut = ap;
112 line[pos] = g * ap;
113 pos = (pos + 1) % N;
114 out[n] = y;
115 }
116 return out;
119// Decaying sinusoids. partials: [ratio, amplitude, t60 as a fraction of the
120// fundamental's t60]; tremolo: { rate (Hz), depth }. Partials past 0.45 of
121// the sample rate are left out.
122function modal(sr, freq, t60, partials, { tremolo } = {}) {
123 const len = Math.ceil(sr * t60);
124 const out = new Float32Array(len);
125 for (const [ratio, amp, frac] of partials) {
126 if (ratio * freq > 0.45 * sr) continue;
127 const w = (2 * Math.PI * ratio * freq) / sr;
128 const k = -6.9 / (frac * t60 * sr);
129 for (let n = 0; n < len; n++) out[n] += amp * Math.sin(w * n) * Math.exp(k * n);
130 }
131 if (tremolo) {
132 const w = (2 * Math.PI * tremolo.rate) / sr;
133 for (let n = 0; n < len; n++) out[n] *= 1 - tremolo.depth * (0.5 - 0.5 * Math.cos(w * n));
134 }
135 return out;
138// Two-operator FM (a soft electric piano): the modulator at the pitch, its
139// index fading from about 1.4 to 0.15, so the tone mellows as it rings.
140function fmPiano(sr, freq, t60) {
141 const len = Math.ceil(sr * t60);
142 const out = new Float32Array(len);
143 const w = (2 * Math.PI * freq) / sr;
144 const k = -6.9 / (t60 * sr);
145 const kIndex = -1 / (Math.min(0.25, 0.4 * t60) * sr);
146 for (let n = 0; n < len; n++) {
147 const index = 1.25 * Math.exp(kIndex * n) + 0.15;
148 out[n] = Math.sin(w * n + index * Math.sin(w * n)) * Math.exp(k * n);
149 }
150 return out;
153// The voices, in the order orbits take them. attack: s (raised cosine);
154// render(sr, freq, t60).
155export const VOICES = [
156 { name: 'Harp', attack: 0.004, render: (sr, f, t) => string(sr, f, t) },
157 { name: 'Marimba', attack: 0.002, render: (sr, f, t) => modal(sr, f, t, [[1, 1, 1], [3.93, 0.25, 0.3], [9.2, 0.08, 0.12]]) },
158 { name: 'Vibraphone', attack: 0.003, render: (sr, f, t) => modal(sr, f, t, [[1, 1, 1], [4, 0.15, 0.35], [10, 0.04, 0.1]], { tremolo: { rate: 5, depth: 0.35 } }) },
159 { name: 'Electric piano', attack: 0.003, render: fmPiano },
160 { name: 'Music box', attack: 0.001, render: (sr, f, t) => modal(sr, f, t, [[1, 1, 1], [5.4, 0.2, 0.3], [11.3, 0.06, 0.12]]) },
161 { name: 'Ocarina', attack: 0.035, render: (sr, f, t) => modal(sr, f, t, [[1, 1, 1], [2, 0.15, 0.8], [3, 0.05, 0.6]]) },
162 { name: 'Pizzicato', attack: 0.003, render: (sr, f, t) => string(sr, f, t, { pluck: 0.25 }) },
163 { name: 'Kalimba', attack: 0.0015, render: (sr, f, t) => modal(sr, f, t, [[1, 1, 1], [2, 0.06, 0.3], [6.27, 0.18, 0.12]]) },
164];
166// A biquad filter applied to x, in place: [b0, b1, b2, a1, a2] (a0 = 1).
167function biquad(x, [b0, b1, b2, a1, a2]) {
168 let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
169 for (let n = 0; n < x.length; n++) {
170 const y = b0 * x[n] + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2;
171 x2 = x1; x1 = x[n]; y2 = y1; y1 = y;
172 x[n] = y;
173 }
176// The K-weighting of ITU-R BS.1770 at sample rate sr (its two stages, from
177// their analog prototypes): a high shelf, then a high-pass.
178function kWeighting(sr) {
179 let K = Math.tan((Math.PI * 1681.974450955533) / sr);
180 const Q1 = 0.7071752369554196;
181 const Vh = 10 ** (3.999843853973347 / 20);
182 const Vb = Vh ** 0.4996667741545416;
183 let a0 = 1 + K / Q1 + K * K;
184 const shelf = [(Vh + (Vb * K) / Q1 + K * K) / a0, (2 * (K * K - Vh)) / a0, (Vh - (Vb * K) / Q1 + K * K) / a0, (2 * (K * K - 1)) / a0, (1 - K / Q1 + K * K) / a0];
185 K = Math.tan((Math.PI * 38.13547087602444) / sr);
186 const Q2 = 0.5003270373238773;
187 a0 = 1 + K / Q2 + K * K;
188 const highpass = [1, -2, 1, (2 * (K * K - 1)) / a0, (1 - K / Q2 + K * K) / a0];
189 return [shelf, highpass];
192// The K-weighted RMS of x (BS.1770's measure of loudness, without gating).
193function loudness(x, sr) {
194 const y = Float32Array.from(x);
195 for (const stage of kWeighting(sr)) biquad(y, stage);
196 let ss = 0;
197 for (let n = 0; n < y.length; n++) ss += y[n] * y[n];
198 return Math.sqrt(ss / y.length);
201// A voice's note at freq ringing for t60 s, as an AudioBuffer: with its
202// attack and a short fade at the end, matched in loudness.
203export function renderNote(ctx, voice, freq, t60) {
204 const sr = ctx.sampleRate;
205 const out = voice.render(sr, freq, t60);
206 const att = Math.max(1, Math.floor(voice.attack * sr));
207 const fade = Math.min(Math.floor(0.05 * sr), Math.floor(out.length / 4));
208 for (let n = 0; n < out.length; n++) {
209 const a = n < att ? 0.5 - 0.5 * Math.cos((Math.PI * n) / att) : 1;
210 out[n] *= a * Math.min(1, (out.length - n) / fade);
211 }
212 const onset = out.subarray(0, Math.min(out.length, Math.floor(LOUD_WINDOW * sr)));
213 const scale = LOUDNESS / (loudness(onset, sr) + 1e-12);
214 for (let n = 0; n < out.length; n++) out[n] *= scale;
215 const buf = ctx.createBuffer(1, out.length, sr);
216 buf.copyToChannel(out, 0);
217 return buf;
220// An exponentially decaying stereo noise tail, for the reverb.
221function reverbImpulse(ctx, seconds = 1.6) {
222 const len = Math.floor(ctx.sampleRate * seconds);
223 const buf = ctx.createBuffer(2, len, ctx.sampleRate);
224 for (let ch = 0; ch < 2; ch++) {
225 const data = buf.getChannelData(ch);
226 // noise, low-passed (about 2 kHz) so the tail is warm, not hissy
227 let lp = 0;
228 for (let n = 0; n < len; n++) {
229 lp += 0.25 * (Math.random() * 2 - 1 - lp);
230 data[n] = lp * Math.exp((-6.9 * n) / len);
231 }
232 }
233 return buf;
236export function createSynth() {
237 const ctx = new AudioContext();
238 const master = ctx.createGain();
239 const limiter = ctx.createDynamicsCompressor();
240 limiter.threshold.value = -6;
241 limiter.knee.value = 6;
242 limiter.ratio.value = 12;
243 limiter.attack.value = 0.003;
244 limiter.release.value = 0.2;
245 const tone = ctx.createBiquadFilter(); // a soft roll-off of the highs
246 tone.type = 'lowpass';
247 tone.frequency.value = 3500;
248 tone.Q.value = 0.5;
249 const dry = ctx.createGain();
250 const wet = ctx.createGain();
251 wet.gain.value = 0.45;
252 const reverb = ctx.createConvolver();
253 reverb.buffer = reverbImpulse(ctx);
254 tone.connect(dry);
255 dry.connect(master);
256 dry.connect(reverb).connect(wet).connect(master);
257 master.connect(limiter).connect(ctx.destination);
258 const cache = new Map();
259 // per channel (an orbit's voice), its notes still sounding, oldest first;
260 // past MAX_SOUNDING the oldest is faded out, so fast tempos with long
261 // sustains stay light (at 16 notes/s, 64 notes is 4 s)
262 const MAX_SOUNDING = 64;
263 const sounding = new Map();
264 let sustain = SUSTAIN.default;
266 return {
267 ctx,
268 setVolume(v) { master.gain.setTargetAtTime(v, ctx.currentTime, 0.02); },
269 // the time (s) for each note to fade by 60 dB, for the notes from now on
270 setSustain(s) {
271 if (s === sustain) return;
272 sustain = s;
273 cache.clear();
274 },
275 // a note of VOICES[voice] at freq, at time `when` (the context's clock),
276 // panned by pan in [-1, 1], at level gain
277 play(voice, freq, when, pan = 0, gain = 1) {
278 const key = `${voice}:${Math.round(freq * 10)}`;
279 let buf = cache.get(key);
280 if (!buf) {
281 buf = renderNote(ctx, VOICES[voice], freq, sustain);
282 if (cache.size > 400) cache.clear();
283 cache.set(key, buf);
284 }
285 const src = ctx.createBufferSource();
286 src.buffer = buf;
287 const level = ctx.createGain();
288 level.gain.value = gain;
289 const panner = ctx.createStereoPanner();
290 panner.pan.value = pan;
291 src.connect(level).connect(panner).connect(tone);
292 const t = Math.max(when, ctx.currentTime);
293 src.start(t);
294 const list = sounding.get(voice) ?? [];
295 const end = t + buf.duration;
296 list.push({ src, level, end });
297 // drop those that have finished by now, then fade the excess
298 while (list.length && list[0].end < ctx.currentTime) list.shift();
299 while (list.length > MAX_SOUNDING) {
300 const old = list.shift();
301 old.level.gain.setValueAtTime(old.level.gain.value, t);
302 old.level.gain.linearRampToValueAtTime(0, t + 0.04);
303 old.src.stop(t + 0.05);
304 }
305 sounding.set(voice, list);
306 },
307 };
↑↓ move↵openescclose