// 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 per // track). 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. // Each track has its own gain (its volume) and sustain. The presets of an // uploaded SoundFont (js/soundfont.js) are more voices: their samples play // as recorded (sustain doesn't apply), at a MIDI velocity set per track, // matched in loudness to the others at velocity 100 near middle C. 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 export const OCTAVES = 3; // by default, 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, octaves = OCTAVES) { 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; } // The audio worklet that records the output: stereo frames, posted in blocks // of 8192 (and what is left when told to stop). const CAPTURE_WORKLET = ` class CaptureTap extends AudioWorkletProcessor { constructor() { super(); this.n = 0; this.l = new Float32Array(8192); this.r = new Float32Array(8192); this.done = false; this.port.onmessage = () => { this.post(true); this.done = true; }; } post(last) { this.port.postMessage({ l: this.l.slice(0, this.n), r: this.r.slice(0, this.n), last }); this.n = 0; } process(inputs) { if (this.done) return false; const ch = inputs[0]; if (ch.length) { const a = ch[0], b = ch[1] || ch[0]; for (let i = 0; i < a.length; i++) { this.l[this.n] = a[i]; this.r[this.n] = b[i]; if (++this.n === this.l.length) this.post(false); } } return true; } } registerProcessor('capture-tap', CaptureTap); `; 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); // rendered notes, per voice, sustain and pitch const cache = new Map(); // per track: its gain (the track's volume) and 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 tracks = new Map(); const track = (id) => { let tr = tracks.get(id); if (!tr) { const gain = ctx.createGain(); gain.connect(tone); tr = { gain, sounding: [] }; tracks.set(id, tr); } return tr; }; // per SoundFont instrument, its loudness match (at velocity 100 near middle C) const sfGains = new WeakMap(); const sfGain = (inst) => { if (!sfGains.has(inst)) { const { x, rate } = inst.reference(100, LOUD_WINDOW); sfGains.set(inst, LOUDNESS / (loudness(x, rate) + 1e-12)); } return sfGains.get(inst); }; return { ctx, // the master volume setVolume(v) { master.gain.setTargetAtTime(v, ctx.currentTime, 0.02); }, // the output as heard (after the master volume and limiter), as a // MediaStream, for recording stream() { if (!this.tap) { this.tap = ctx.createMediaStreamDestination(); limiter.connect(this.tap); } return this.tap.stream; }, // Record the output as heard, sample for sample: onData(left, right) // gets Float32Arrays of frames as they come (at ctx.sampleRate). // Resolves to stop(), which resolves once the last frames are in. async capture(onData) { if (!this.tapModule) { const url = URL.createObjectURL(new Blob([CAPTURE_WORKLET], { type: 'text/javascript' })); this.tapModule = ctx.audioWorklet.addModule(url).finally(() => URL.revokeObjectURL(url)); } await this.tapModule; const node = new AudioWorkletNode(ctx, 'capture-tap', { numberOfInputs: 1, numberOfOutputs: 1, outputChannelCount: [1], channelCount: 2, channelCountMode: 'explicit', channelInterpretation: 'speakers', }); // (an output to the destination, silent, so the node is pulled) const mute = ctx.createGain(); mute.gain.value = 0; limiter.connect(node); node.connect(mute).connect(ctx.destination); let finish; const finished = new Promise((r) => { finish = r; }); node.port.onmessage = (e) => { if (e.data.l.length) onData(e.data.l, e.data.r); if (e.data.last) finish(); }; return async () => { node.port.postMessage('stop'); // (a suspended context sends nothing more) await Promise.race([finished, new Promise((r) => setTimeout(r, 1000))]); limiter.disconnect(node); node.disconnect(); mute.disconnect(); }; }, // a track's volume (its notes, sounding and to come) setTrackVolume(id, v) { track(id).gain.gain.setTargetAtTime(v, ctx.currentTime, 0.02); }, // a track removed: its notes fade out removeTrack(id) { const tr = tracks.get(id); if (!tr) return; tracks.delete(id); for (const n of tr.sounding) n.stop(ctx.currentTime); setTimeout(() => tr.gain.disconnect(), 200); }, // a note on track `id` of `voice` (an index into VOICES, or a SoundFont // instrument from makeInstrument, played at MIDI velocity vel) at freq, // at time `when` (the context's clock), panned by pan in [-1, 1], at // level gain; the built-in voices ring for `sustain` s; mono: the track's // notes still sounding fade out as it starts play(id, voice, freq, when, { pan = 0, gain = 1, sustain = SUSTAIN.default, vel = 100, mono = false } = {}) { const tr = track(id); const level = ctx.createGain(); const panner = ctx.createStereoPanner(); panner.pan.value = pan; level.connect(panner).connect(tr.gain); const t = Math.max(when, ctx.currentTime); let sound; // { end, stop(at): end it at `at` } if (typeof voice !== 'number') { level.gain.value = gain * sfGain(voice); sound = voice.play(ctx, 69 + 12 * Math.log2(freq / 440), vel, t, level); } else { const key = `${voice}:${sustain.toFixed(2)}:${Math.round(freq * 10)}`; let buf = cache.get(key); if (!buf) { buf = renderNote(ctx, VOICES[voice], freq, sustain); if (cache.size > 800) cache.clear(); cache.set(key, buf); } const src = ctx.createBufferSource(); src.buffer = buf; level.gain.value = gain; src.connect(level); src.start(t); sound = { end: t + buf.duration, stop: (at) => src.stop(at) }; } // a note stopped at `at` (perhaps still to come) fades out over 40 ms // (its level is steady, so the ramp starts from where it is) const note = { start: t, end: sound.end, stop(at) { if (at >= this.end) return; level.gain.setValueAtTime(level.gain.value, Math.max(at, ctx.currentTime)); level.gain.linearRampToValueAtTime(0, Math.max(at, ctx.currentTime) + 0.04); sound.stop(Math.max(at, ctx.currentTime) + 0.05); this.end = Math.min(this.end, at + 0.05); }, }; const list = tr.sounding; if (mono) { for (const n of list) if (n.start < t) n.stop(t); } list.push(note); // 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) list.shift().stop(t); }, }; }