// The instruments the orbits play, and the mapping from a point's x to its // pitch. Each orbit plays its own voice, so several can be told apart. // // Each note is rendered once into an AudioBuffer (cached per voice, pitch // and sustain), given a soft attack and a short fade at the end, and matched // in loudness to all the others. Every voice and pitch rings for the same // time: the sustain, the time for the fundamental to fade by 60 dB (set by // the page). So the voices differ in timbre and attack, not in how long // they ring, and loudness is matched by 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): the same for every voice, pitch and sustain. // - Strings (harp, pizzicato) are Karplus-Strong: the string starts in a // rounded, fingertip-plucked shape and circulates in a delay line of one // period, through a gentle low-pass (so the high harmonics die away first, // leaving a warm tone) and a first-order all-pass that tunes the // fractional part of the period. // - Bars, tines and the ocarina are modal: a few decaying sinusoids, at the // instrument's partial ratios (marimba 1 : 3.93 : 9.2, vibraphone // 1 : 4 : 10 with tremolo, and so on). // - The electric piano is two-operator FM with a fading modulation index. // Everything goes through a soft low-pass, a dark synthetic reverb and a // limiter. export const DEFAULT_SCALE = 'Minor pentatonic'; 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 left edge of the view const OCTAVES = 3; // up to C6 at the right edge // The pitch (Hz) for u in [0, 1] (the left to right edge of the view): the // notes of the scale in the given key (0 = C, ..., 11 = B) that lie within // OCTAVES octaves from LOW, spread evenly across the view; 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: 2 }; // s const LOUD_WINDOW = 0.3; // s const LOUDNESS = 0.12; // target K-weighted RMS over LOUD_WINDOW // Karplus-Strong string: t60 (s, for the fundamental to fade by 60 dB), // pluck (where along the string it is plucked: smaller is brighter). function string(sr, freq, t60, { pluck = 0.15 } = {}) { const len = Math.ceil(sr * t60); const out = new Float32Array(len); // Loop delay L = sr / freq: N samples, plus one for the [1/4, 1/2, 1/4] // loop filter, plus the all-pass's d (kept in [0.5, 1.5), where it is // accurate and well behaved). const L = sr / freq; const N = Math.floor(L - 1.5); const d = L - 1 - N; const c = (1 - d) / (1 + d); // the loop filter takes cos^2(pi f / sr) off each harmonic per pass, so // the highs die away within a few periods; the loop gain makes up the // fundamental's share, so it still fades over t60 const H1 = Math.cos((Math.PI * freq) / sr) ** 2; const g = Math.min(0.99995, 10 ** (-3 / (t60 * freq)) / H1); // the pluck: the string's initial shape, a triangle peaked at `pluck` of // its length (harmonics falling as 1/k^2: at 0.15, about -8, -14, -21 dB // for the 2nd to 4th), its corner rounded off as by a fingertip, with a // trace of noise const tri = new Float32Array(N); for (let i = 0; i < N; i++) { const u = (i + 0.5) / N; tri[i] = u < pluck ? u / pluck : (1 - u) / (1 - pluck); } const w = Math.max(1, Math.round(N / 25)); const line = new Float32Array(N); for (let i = 0; i < N; i++) { let acc = 0; for (let k = -w; k <= w; k++) acc += tri[(i + k + N) % N]; line[i] = acc / (2 * w + 1); } let mean = 0; for (let i = 0; i < N; i++) { line[i] += 0.02 * (Math.random() * 2 - 1); mean += line[i] / N; } for (let i = 0; i < N; i++) line[i] -= mean; let pos = 0; let y1 = 0; let y2 = 0; let apIn = 0; let apOut = 0; for (let n = 0; n < len; n++) { const y = line[pos]; const lp = 0.25 * y + 0.5 * y1 + 0.25 * y2; y2 = y1; y1 = y; const ap = c * lp + apIn - c * apOut; apIn = lp; apOut = ap; line[pos] = g * ap; pos = (pos + 1) % N; out[n] = y; } return out; } // Decaying sinusoids. partials: [ratio, amplitude, t60 as a fraction of the // fundamental's t60]; tremolo: { rate (Hz), depth }. Partials past 0.45 of // the sample rate are left out. function modal(sr, freq, t60, partials, { tremolo } = {}) { const len = Math.ceil(sr * t60); const out = new Float32Array(len); for (const [ratio, amp, frac] of partials) { if (ratio * freq > 0.45 * sr) continue; const w = (2 * Math.PI * ratio * freq) / sr; const k = -6.9 / (frac * t60 * sr); for (let n = 0; n < len; n++) out[n] += amp * Math.sin(w * n) * Math.exp(k * n); } if (tremolo) { const w = (2 * Math.PI * tremolo.rate) / sr; for (let n = 0; n < len; n++) out[n] *= 1 - tremolo.depth * (0.5 - 0.5 * Math.cos(w * n)); } return out; } // Two-operator FM (a soft electric piano): the modulator at the pitch, its // index fading from about 1.4 to 0.15, so the tone mellows as it rings. function fmPiano(sr, freq, t60) { const len = Math.ceil(sr * t60); const out = new Float32Array(len); const w = (2 * Math.PI * freq) / sr; const k = -6.9 / (t60 * sr); const kIndex = -1 / (Math.min(0.25, 0.4 * t60) * sr); for (let n = 0; n < len; n++) { const index = 1.25 * Math.exp(kIndex * n) + 0.15; out[n] = Math.sin(w * n + index * Math.sin(w * n)) * Math.exp(k * n); } return out; } // The voices, in the order orbits take them. attack: s (raised cosine); // render(sr, freq, t60). export const VOICES = [ { name: 'Harp', attack: 0.004, render: (sr, f, t) => string(sr, f, t) }, { 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]]) }, { 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 } }) }, { name: 'Electric piano', attack: 0.003, render: fmPiano }, { 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]]) }, { 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]]) }, { name: 'Pizzicato', attack: 0.003, render: (sr, f, t) => string(sr, f, t, { pluck: 0.25 }) }, { 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]]) }, ]; // 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 voice'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 = 3500; 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(); // per channel (an orbit's voice), its notes still sounding, oldest first; // past MAX_SOUNDING the oldest is faded out, so fast tempos with long // sustains stay light (at 16 notes/s, 64 notes is 4 s) const MAX_SOUNDING = 64; const sounding = new Map(); let sustain = SUSTAIN.default; 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(); }, // a note of VOICES[voice] at freq, at time `when` (the context's clock), // panned by pan in [-1, 1], at level gain play(voice, freq, when, pan = 0, gain = 1) { const key = `${voice}:${Math.round(freq * 10)}`; let buf = cache.get(key); if (!buf) { buf = renderNote(ctx, VOICES[voice], freq, sustain); if (cache.size > 400) cache.clear(); cache.set(key, buf); } const src = ctx.createBufferSource(); src.buffer = buf; const level = ctx.createGain(); level.gain.value = gain; const panner = ctx.createStereoPanner(); panner.pan.value = pan; src.connect(level).connect(panner).connect(tone); const t = Math.max(when, ctx.currentTime); src.start(t); const list = sounding.get(voice) ?? []; const end = t + buf.duration; list.push({ src, level, end }); // drop those that have finished by now, then fade the excess while (list.length && list[0].end < ctx.currentTime) list.shift(); while (list.length > MAX_SOUNDING) { const old = list.shift(); old.level.gain.setValueAtTime(old.level.gain.value, t); old.level.gain.linearRampToValueAtTime(0, t + 0.04); old.src.stop(t + 0.05); } sounding.set(voice, list); }, }; }