726adb6Listening for convergence: MCMC chains on a 2D mixture, sonifiedJeremy Magland 1// The sound of the chains, and the mapping from a point's θ₁ to its pitch.
2//
3// Every note is a crossfade (equal power) between two tones at its pitch,
4// set by θ₂: a soft, nearly pure tone at the bottom of the plane, and a
5// bright, buzzy, nasal one at the top (a sawtooth-like spectrum, its
6// harmonics falling as 1/k^0.8, with a formant around 2 kHz). Both are
7// rendered once per pitch and sustain into AudioBuffers from one period of
8// their waveform (a wavetable), with a soft attack, an exponential decay
9// (the sustain is the time to fade by 60 dB) and a short fade at the end,
10// and matched in loudness: the RMS over each note's onset (its first
11// LOUD_WINDOW s) after the K-weighting filter of ITU-R BS.1770 (a high shelf
12// of +4 dB above about 1.7 kHz, where the ear is most sensitive, and a
13// high-pass at 38 Hz). So top and bottom differ in timbre only, not in
14// loudness. Under the notes, an optional drone (setDrone). Everything goes
15// through a soft low-pass (6 kHz), a dark synthetic reverb and a limiter.
17export const DEFAULT_SCALE = 'Chromatic';
18export const KEYS = ['C', 'C♯', 'D', 'E♭', 'E', 'F', 'F♯', 'G', 'A♭', 'A', 'B♭', 'B'];
19export const DEFAULT_KEY = 9; // A
21// Scales as semitone offsets within an octave; null: continuous pitch.
22export const SCALES = [
23 { name: 'Major pentatonic', steps: [0, 2, 4, 7, 9] },
24 { name: 'Minor pentatonic', steps: [0, 3, 5, 7, 10] },
25 { name: 'Major', steps: [0, 2, 4, 5, 7, 9, 11] },
26 { name: 'Natural minor', steps: [0, 2, 3, 5, 7, 8, 10] },
27 { name: 'Harmonic minor', steps: [0, 2, 3, 5, 7, 8, 11] },
28 { name: 'Whole tone', steps: [0, 2, 4, 6, 8, 10] },
29 { name: 'Chromatic', steps: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] },
30 { name: 'Continuous', steps: null },
31];
33const LOW = 130.81; // C3, the pitch at the low end of the range
34const OCTAVES = 3; // up to C6 at the high end
36// The pitch (Hz) for u in [0, 1] (the low to high end of the range): the
37// notes of the scale in the given key (0 = C, ..., 11 = B) that lie within
38// OCTAVES octaves from LOW, spread evenly across the range; or continuous.
39// The register stays put when the key changes, so a key change shifts the
40// harmony, like a chord change.
41export function pitchOf(u, scale, key = 0) {
42 u = Math.min(1, Math.max(0, u));
43 if (!scale.steps) return LOW * 2 ** (OCTAVES * u);
44 const notes = [];
45 for (let s = 0; s <= 12 * OCTAVES; s++) {
46 if (scale.steps.includes((((s - key) % 12) + 12) % 12)) notes.push(s);
47 }
48 return LOW * 2 ** (notes[Math.round(u * (notes.length - 1))] / 12);
49}
51export const SUSTAIN = { min: 0.1, max: 4, step: 0.1, default: 0.6 }; // s
52const LOUD_WINDOW = 0.3; // s
53const LOUDNESS = 0.12; // target K-weighted RMS over LOUD_WINDOW
55const TABLE = 2048; // samples per period in the wavetables
57// A tone at freq ringing for t60 s (the time to fade by 60 dB), with the
58// harmonic amplitudes amp(k, freq), k = 1, 2, ... up to maxHz (and 0.45 of
59// the sample rate): one period built additively, then read around at freq.
60function tone(sr, freq, t60, amp, maxHz) {
61 const K = Math.max(1, Math.floor(Math.min(maxHz, 0.45 * sr) / freq));
62 const table = new Float32Array(TABLE + 1);
63 for (let k = 1; k <= K; k++) {
64 const a = amp(k, freq);
65 if (!a) continue;
66 for (let i = 0; i < TABLE; i++) table[i] += a * Math.sin((2 * Math.PI * k * i) / TABLE);
67 }
68 table[TABLE] = table[0];
69 const len = Math.ceil(sr * t60);
70 const out = new Float32Array(len);
71 const step = (freq * TABLE) / sr;
72 const decay = -6.9 / (t60 * sr);
73 let ph = 0;
74 for (let n = 0; n < len; n++) {
75 const i = Math.floor(ph);
76 const f = ph - i;
77 out[n] = ((1 - f) * table[i] + f * table[i + 1]) * Math.exp(decay * n);
78 ph += step;
79 if (ph >= TABLE) ph -= TABLE;
80 }
81 return out;
82}
84// The two tones θ₂ fades between. attack: s (raised cosine);
85// render(sr, freq, t60).
86export const TONES = [
87 {
88 name: 'Pure',
89 attack: 0.005,
90 // the fundamental, with a trace of the 2nd and 3rd harmonics, so low
91 // notes still sound on small speakers
92 render: (sr, f, t) => tone(sr, f, t, (k) => [0, 1, 0.08, 0.02][k] ?? 0, 4 * f),
93 },
94 {
95 name: 'Buzzy',
96 attack: 0.003,
97 render: (sr, f, t) => tone(sr, f, t, (k, fr) => k ** -0.8 * (1 + 2.5 * Math.exp(-(((k * fr - 2000) / 900) ** 2))), 7000),
98 },
99];
101// A biquad filter applied to x, in place: [b0, b1, b2, a1, a2] (a0 = 1).
102function biquad(x, [b0, b1, b2, a1, a2]) {
103 let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
104 for (let n = 0; n < x.length; n++) {
105 const y = b0 * x[n] + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2;
106 x2 = x1; x1 = x[n]; y2 = y1; y1 = y;
107 x[n] = y;
108 }
109}
111// The K-weighting of ITU-R BS.1770 at sample rate sr (its two stages, from
112// their analog prototypes): a high shelf, then a high-pass.
113function kWeighting(sr) {
114 let K = Math.tan((Math.PI * 1681.974450955533) / sr);
115 const Q1 = 0.7071752369554196;
116 const Vh = 10 ** (3.999843853973347 / 20);
117 const Vb = Vh ** 0.4996667741545416;
118 let a0 = 1 + K / Q1 + K * K;
119 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];
120 K = Math.tan((Math.PI * 38.13547087602444) / sr);
121 const Q2 = 0.5003270373238773;
122 a0 = 1 + K / Q2 + K * K;
123 const highpass = [1, -2, 1, (2 * (K * K - 1)) / a0, (1 - K / Q2 + K * K) / a0];
124 return [shelf, highpass];
125}
127// The K-weighted RMS of x (BS.1770's measure of loudness, without gating).
128function loudness(x, sr) {
129 const y = Float32Array.from(x);
130 for (const stage of kWeighting(sr)) biquad(y, stage);
131 let ss = 0;
132 for (let n = 0; n < y.length; n++) ss += y[n] * y[n];
133 return Math.sqrt(ss / y.length);
134}
136// A tone's note at freq ringing for t60 s, as an AudioBuffer: with its
137// attack and a short fade at the end, matched in loudness.
138export function renderNote(ctx, voice, freq, t60) {
139 const sr = ctx.sampleRate;
140 const out = voice.render(sr, freq, t60);
141 const att = Math.max(1, Math.floor(voice.attack * sr));
142 const fade = Math.min(Math.floor(0.05 * sr), Math.floor(out.length / 4));
143 for (let n = 0; n < out.length; n++) {
144 const a = n < att ? 0.5 - 0.5 * Math.cos((Math.PI * n) / att) : 1;
145 out[n] *= a * Math.min(1, (out.length - n) / fade);
146 }
147 const onset = out.subarray(0, Math.min(out.length, Math.floor(LOUD_WINDOW * sr)));
148 const scale = LOUDNESS / (loudness(onset, sr) + 1e-12);
149 for (let n = 0; n < out.length; n++) out[n] *= scale;
150 const buf = ctx.createBuffer(1, out.length, sr);
151 buf.copyToChannel(out, 0);
152 return buf;
153}
155// An exponentially decaying stereo noise tail, for the reverb.
156function reverbImpulse(ctx, seconds = 1.6) {
157 const len = Math.floor(ctx.sampleRate * seconds);
158 const buf = ctx.createBuffer(2, len, ctx.sampleRate);
159 for (let ch = 0; ch < 2; ch++) {
160 const data = buf.getChannelData(ch);
161 // noise, low-passed (about 2 kHz) so the tail is warm, not hissy
162 let lp = 0;
163 for (let n = 0; n < len; n++) {
164 lp += 0.25 * (Math.random() * 2 - 1 - lp);
165 data[n] = lp * Math.exp((-6.9 * n) / len);
166 }
167 }
168 return buf;
169}
171export function createSynth() {
172 const ctx = new AudioContext();
173 const master = ctx.createGain();
174 const limiter = ctx.createDynamicsCompressor();
175 limiter.threshold.value = -6;
176 limiter.knee.value = 6;
177 limiter.ratio.value = 12;
178 limiter.attack.value = 0.003;
179 limiter.release.value = 0.2;
180 const tone = ctx.createBiquadFilter(); // a soft roll-off of the highs
181 tone.type = 'lowpass';
182 tone.frequency.value = 6000;
183 tone.Q.value = 0.5;
184 const dry = ctx.createGain();
185 const wet = ctx.createGain();
186 wet.gain.value = 0.45;
187 const reverb = ctx.createConvolver();
188 reverb.buffer = reverbImpulse(ctx);
189 tone.connect(dry);
190 dry.connect(master);
191 dry.connect(reverb).connect(wet).connect(master);
192 master.connect(limiter).connect(ctx.destination);
193 const cache = new Map();
194 // the notes still sounding, oldest first; past MAX_SOUNDING the oldest is
195 // faded out, so fast tempos with many chains and long sustains stay light
196 // (at 400 notes/s, 192 notes is about half a second)
197 const MAX_SOUNDING = 192;
198 let sounding = [];
199 let sustain = SUSTAIN.default;
201 // the agreement drone: per chain, a soft triangle at the root (layer 0)
202 // and one at the fifth (layer 1), each detuned by the page; with every
203 // chain in tune, a plain fifth
204 const droneOut = ctx.createGain();
205 droneOut.gain.value = 0;
206 droneOut.connect(tone);
207 const droneLayers = [[], []];
208 let droneRoot = 220;
209 const droneFreq = (layer) => droneRoot * (layer ? 1.5 : 1);
211 return {
212 ctx,
213 setVolume(v) { master.gain.setTargetAtTime(v, ctx.currentTime, 0.02); },
214 // the time (s) for each note to fade by 60 dB, for the notes from now on
215 setSustain(s) {
216 if (s === sustain) return;
217 sustain = s;
218 cache.clear();
219 },
220 // the drone: level in [0, 1] (0: silent), and cents[layer][chain]
221 setDrone(level, cents) {
222 const now = ctx.currentTime;
223 droneOut.gain.setTargetAtTime(0.12 * level, now, 0.15);
224 cents.forEach((list, layer) => {
225 const oscs = droneLayers[layer];
226 while (oscs.length < list.length) {
227 const osc = ctx.createOscillator();
228 osc.type = 'triangle';
229 osc.frequency.value = droneFreq(layer);
230 const g = ctx.createGain();
231 g.gain.value = 0;
232 osc.connect(g).connect(droneOut);
233 osc.start();
234 oscs.push({ osc, g });
235 }
236 while (oscs.length > list.length) {
237 const { osc, g } = oscs.pop();
238 g.gain.setTargetAtTime(0, now, 0.05);
239 osc.stop(now + 0.4);
240 }
241 const share = (layer ? 0.6 : 1) / Math.sqrt(list.length);
242 oscs.forEach(({ osc, g }, k) => {
243 osc.detune.setTargetAtTime(list[k], now, 0.25);
244 g.gain.setTargetAtTime(share, now, 0.1);
245 });
246 });
247 },
248 setDroneRoot(f) {
249 droneRoot = f;
250 droneLayers.forEach((oscs, layer) => {
251 for (const { osc } of oscs) osc.frequency.setTargetAtTime(droneFreq(layer), ctx.currentTime, 0.05);
252 });
253 },
254 // a note at freq, at time `when` (the context's clock), panned by pan in
255 // [-1, 1], at level gain, its timbre bright in [0, 1] (0: pure, 1: buzzy)
256 play(freq, when, { pan = 0, gain = 1, bright = 0.5 } = {}) {
257 const level = ctx.createGain();
258 level.gain.value = gain;
259 const panner = ctx.createStereoPanner();
260 panner.pan.value = pan;
261 level.connect(panner).connect(tone);
262 const srcs = TONES.map((voice, i) => {
263 const key = `${i}:${Math.round(freq * 10)}`;
264 let buf = cache.get(key);
265 if (!buf) {
266 buf = renderNote(ctx, voice, freq, sustain);
267 if (cache.size > 400) cache.clear();
268 cache.set(key, buf);
269 }
270 const src = ctx.createBufferSource();
271 src.buffer = buf;
272 const mix = ctx.createGain();
273 mix.gain.value = i ? Math.sin((Math.PI / 2) * bright) : Math.cos((Math.PI / 2) * bright);
274 src.connect(mix).connect(level);
275 return src;
276 });
277 const buf = srcs[0].buffer;
278 const t = Math.max(when, ctx.currentTime);
279 for (const src of srcs) src.start(t);
280 const end = t + buf.duration;
281 sounding.push({ srcs, level, end });
282 // drop those that have finished by now, then fade the excess
283 if (sounding.length > MAX_SOUNDING) sounding = sounding.filter((n) => n.end >= ctx.currentTime);
284 while (sounding.length > MAX_SOUNDING) {
285 const old = sounding.shift();
286 old.level.gain.setValueAtTime(old.level.gain.value, t);
287 old.level.gain.linearRampToValueAtTime(0, t + 0.04);
288 for (const src of old.srcs) src.stop(t + 0.05);
289 }
290 },
291 };
292}