// The sound of the chains, and the mapping from a point's θ₁ to its pitch. // // Every note is a crossfade (equal power) between two tones at its pitch, // set by θ₂: a soft, nearly pure tone at the bottom of the plane, and a // bright, buzzy, nasal one at the top (a sawtooth-like spectrum, its // harmonics falling as 1/k^0.8, with a formant around 2 kHz). Both are // rendered once per pitch and sustain into AudioBuffers from one period of // their waveform (a wavetable), with a soft attack, an exponential decay // (the sustain is the time to fade by 60 dB) and a short fade at the end, // and matched in loudness: the RMS over each note's onset (its first // LOUD_WINDOW s) after the K-weighting filter of ITU-R BS.1770 (a high shelf // of +4 dB above about 1.7 kHz, where the ear is most sensitive, and a // high-pass at 38 Hz). So top and bottom differ in timbre only, not in // loudness. Under the notes, an optional drone (setDrone). Everything goes // through a soft low-pass (6 kHz), a dark synthetic reverb and a limiter. export const DEFAULT_SCALE = 'Chromatic'; export const KEYS = ['C', 'C♯', 'D', 'E♭', 'E', 'F', 'F♯', 'G', 'A♭', 'A', 'B♭', 'B']; export const DEFAULT_KEY = 9; // A // Scales as semitone offsets within an octave; null: continuous pitch. export const SCALES = [ { name: 'Major pentatonic', steps: [0, 2, 4, 7, 9] }, { name: 'Minor pentatonic', steps: [0, 3, 5, 7, 10] }, { name: 'Major', steps: [0, 2, 4, 5, 7, 9, 11] }, { name: 'Natural minor', steps: [0, 2, 3, 5, 7, 8, 10] }, { name: 'Harmonic minor', steps: [0, 2, 3, 5, 7, 8, 11] }, { name: 'Whole tone', steps: [0, 2, 4, 6, 8, 10] }, { name: 'Chromatic', steps: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] }, { name: 'Continuous', steps: null }, ]; const LOW = 130.81; // C3, the pitch at the low end of the range const OCTAVES = 3; // up to C6 at the high end // The pitch (Hz) for u in [0, 1] (the low to high end of the range): the // notes of the scale in the given key (0 = C, ..., 11 = B) that lie within // OCTAVES octaves from LOW, spread evenly across the range; or continuous. // The register stays put when the key changes, so a key change shifts the // harmony, like a chord change. export function pitchOf(u, scale, key = 0) { u = Math.min(1, Math.max(0, u)); if (!scale.steps) return LOW * 2 ** (OCTAVES * u); const notes = []; for (let s = 0; s <= 12 * OCTAVES; s++) { if (scale.steps.includes((((s - key) % 12) + 12) % 12)) notes.push(s); } return LOW * 2 ** (notes[Math.round(u * (notes.length - 1))] / 12); } export const SUSTAIN = { min: 0.1, max: 4, step: 0.1, default: 0.6 }; // s const LOUD_WINDOW = 0.3; // s const LOUDNESS = 0.12; // target K-weighted RMS over LOUD_WINDOW const TABLE = 2048; // samples per period in the wavetables // A tone at freq ringing for t60 s (the time to fade by 60 dB), with the // harmonic amplitudes amp(k, freq), k = 1, 2, ... up to maxHz (and 0.45 of // the sample rate): one period built additively, then read around at freq. function tone(sr, freq, t60, amp, maxHz) { const K = Math.max(1, Math.floor(Math.min(maxHz, 0.45 * sr) / freq)); const table = new Float32Array(TABLE + 1); for (let k = 1; k <= K; k++) { const a = amp(k, freq); if (!a) continue; for (let i = 0; i < TABLE; i++) table[i] += a * Math.sin((2 * Math.PI * k * i) / TABLE); } table[TABLE] = table[0]; const len = Math.ceil(sr * t60); const out = new Float32Array(len); const step = (freq * TABLE) / sr; const decay = -6.9 / (t60 * sr); let ph = 0; for (let n = 0; n < len; n++) { const i = Math.floor(ph); const f = ph - i; out[n] = ((1 - f) * table[i] + f * table[i + 1]) * Math.exp(decay * n); ph += step; if (ph >= TABLE) ph -= TABLE; } return out; } // The two tones θ₂ fades between. attack: s (raised cosine); // render(sr, freq, t60). export const TONES = [ { name: 'Pure', attack: 0.005, // the fundamental, with a trace of the 2nd and 3rd harmonics, so low // notes still sound on small speakers render: (sr, f, t) => tone(sr, f, t, (k) => [0, 1, 0.08, 0.02][k] ?? 0, 4 * f), }, { name: 'Buzzy', attack: 0.003, render: (sr, f, t) => tone(sr, f, t, (k, fr) => k ** -0.8 * (1 + 2.5 * Math.exp(-(((k * fr - 2000) / 900) ** 2))), 7000), }, ]; // A biquad filter applied to x, in place: [b0, b1, b2, a1, a2] (a0 = 1). function biquad(x, [b0, b1, b2, a1, a2]) { let x1 = 0, x2 = 0, y1 = 0, y2 = 0; for (let n = 0; n < x.length; n++) { const y = b0 * x[n] + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2; x2 = x1; x1 = x[n]; y2 = y1; y1 = y; x[n] = y; } } // The K-weighting of ITU-R BS.1770 at sample rate sr (its two stages, from // their analog prototypes): a high shelf, then a high-pass. function kWeighting(sr) { let K = Math.tan((Math.PI * 1681.974450955533) / sr); const Q1 = 0.7071752369554196; const Vh = 10 ** (3.999843853973347 / 20); const Vb = Vh ** 0.4996667741545416; let a0 = 1 + K / Q1 + K * K; 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]; K = Math.tan((Math.PI * 38.13547087602444) / sr); const Q2 = 0.5003270373238773; a0 = 1 + K / Q2 + K * K; const highpass = [1, -2, 1, (2 * (K * K - 1)) / a0, (1 - K / Q2 + K * K) / a0]; return [shelf, highpass]; } // The K-weighted RMS of x (BS.1770's measure of loudness, without gating). function loudness(x, sr) { const y = Float32Array.from(x); for (const stage of kWeighting(sr)) biquad(y, stage); let ss = 0; for (let n = 0; n < y.length; n++) ss += y[n] * y[n]; return Math.sqrt(ss / y.length); } // A tone's note at freq ringing for t60 s, as an AudioBuffer: with its // attack and a short fade at the end, matched in loudness. export function renderNote(ctx, voice, freq, t60) { const sr = ctx.sampleRate; const out = voice.render(sr, freq, t60); const att = Math.max(1, Math.floor(voice.attack * sr)); const fade = Math.min(Math.floor(0.05 * sr), Math.floor(out.length / 4)); for (let n = 0; n < out.length; n++) { const a = n < att ? 0.5 - 0.5 * Math.cos((Math.PI * n) / att) : 1; out[n] *= a * Math.min(1, (out.length - n) / fade); } const onset = out.subarray(0, Math.min(out.length, Math.floor(LOUD_WINDOW * sr))); const scale = LOUDNESS / (loudness(onset, sr) + 1e-12); for (let n = 0; n < out.length; n++) out[n] *= scale; const buf = ctx.createBuffer(1, out.length, sr); buf.copyToChannel(out, 0); return buf; } // An exponentially decaying stereo noise tail, for the reverb. function reverbImpulse(ctx, seconds = 1.6) { const len = Math.floor(ctx.sampleRate * seconds); const buf = ctx.createBuffer(2, len, ctx.sampleRate); for (let ch = 0; ch < 2; ch++) { const data = buf.getChannelData(ch); // noise, low-passed (about 2 kHz) so the tail is warm, not hissy let lp = 0; for (let n = 0; n < len; n++) { lp += 0.25 * (Math.random() * 2 - 1 - lp); data[n] = lp * Math.exp((-6.9 * n) / len); } } return buf; } export function createSynth() { const ctx = new AudioContext(); const master = ctx.createGain(); const limiter = ctx.createDynamicsCompressor(); limiter.threshold.value = -6; limiter.knee.value = 6; limiter.ratio.value = 12; limiter.attack.value = 0.003; limiter.release.value = 0.2; const tone = ctx.createBiquadFilter(); // a soft roll-off of the highs tone.type = 'lowpass'; tone.frequency.value = 6000; tone.Q.value = 0.5; const dry = ctx.createGain(); const wet = ctx.createGain(); wet.gain.value = 0.45; const reverb = ctx.createConvolver(); reverb.buffer = reverbImpulse(ctx); tone.connect(dry); dry.connect(master); dry.connect(reverb).connect(wet).connect(master); master.connect(limiter).connect(ctx.destination); const cache = new Map(); // the notes still sounding, oldest first; past MAX_SOUNDING the oldest is // faded out, so fast tempos with many chains and long sustains stay light // (at 400 notes/s, 192 notes is about half a second) const MAX_SOUNDING = 192; let sounding = []; let sustain = SUSTAIN.default; // the agreement drone: per chain, a soft triangle at the root (layer 0) // and one at the fifth (layer 1), each detuned by the page; with every // chain in tune, a plain fifth const droneOut = ctx.createGain(); droneOut.gain.value = 0; droneOut.connect(tone); const droneLayers = [[], []]; let droneRoot = 220; const droneFreq = (layer) => droneRoot * (layer ? 1.5 : 1); return { ctx, setVolume(v) { master.gain.setTargetAtTime(v, ctx.currentTime, 0.02); }, // the time (s) for each note to fade by 60 dB, for the notes from now on setSustain(s) { if (s === sustain) return; sustain = s; cache.clear(); }, // the drone: level in [0, 1] (0: silent), and cents[layer][chain] setDrone(level, cents) { const now = ctx.currentTime; droneOut.gain.setTargetAtTime(0.12 * level, now, 0.15); cents.forEach((list, layer) => { const oscs = droneLayers[layer]; while (oscs.length < list.length) { const osc = ctx.createOscillator(); osc.type = 'triangle'; osc.frequency.value = droneFreq(layer); const g = ctx.createGain(); g.gain.value = 0; osc.connect(g).connect(droneOut); osc.start(); oscs.push({ osc, g }); } while (oscs.length > list.length) { const { osc, g } = oscs.pop(); g.gain.setTargetAtTime(0, now, 0.05); osc.stop(now + 0.4); } const share = (layer ? 0.6 : 1) / Math.sqrt(list.length); oscs.forEach(({ osc, g }, k) => { osc.detune.setTargetAtTime(list[k], now, 0.25); g.gain.setTargetAtTime(share, now, 0.1); }); }); }, setDroneRoot(f) { droneRoot = f; droneLayers.forEach((oscs, layer) => { for (const { osc } of oscs) osc.frequency.setTargetAtTime(droneFreq(layer), ctx.currentTime, 0.05); }); }, // a note at freq, at time `when` (the context's clock), panned by pan in // [-1, 1], at level gain, its timbre bright in [0, 1] (0: pure, 1: buzzy) play(freq, when, { pan = 0, gain = 1, bright = 0.5 } = {}) { const level = ctx.createGain(); level.gain.value = gain; const panner = ctx.createStereoPanner(); panner.pan.value = pan; level.connect(panner).connect(tone); const srcs = TONES.map((voice, i) => { const key = `${i}:${Math.round(freq * 10)}`; let buf = cache.get(key); if (!buf) { buf = renderNote(ctx, voice, freq, sustain); if (cache.size > 400) cache.clear(); cache.set(key, buf); } const src = ctx.createBufferSource(); src.buffer = buf; const mix = ctx.createGain(); mix.gain.value = i ? Math.sin((Math.PI / 2) * bright) : Math.cos((Math.PI / 2) * bright); src.connect(mix).connect(level); return src; }); const buf = srcs[0].buffer; const t = Math.max(when, ctx.currentTime); for (const src of srcs) src.start(t); const end = t + buf.duration; sounding.push({ srcs, level, end }); // drop those that have finished by now, then fade the excess if (sounding.length > MAX_SOUNDING) sounding = sounding.filter((n) => n.end >= ctx.currentTime); while (sounding.length > MAX_SOUNDING) { const old = sounding.shift(); old.level.gain.setValueAtTime(old.level.gain.value, t); old.level.gain.linearRampToValueAtTime(0, t + 0.04); for (const src of old.srcs) src.stop(t + 0.05); } }, }; }