// Live sound of an oscillator: the motion is integrated on the audio thread // (oscillator-worklet.js), so it plays until stopped and follows parameter // changes as they happen. // // The worklet's output peaks at about 1 (at most 2, for a driven swing). The // volume slider (0 to 1) sets the gain in decibels, evenly from // VOLUME_MIN_DB to VOLUME_MAX_DB (0 is silent); the default, VOLUME_DEFAULT_DB, // gives a peak of 0.1, since a pure tone is harsh much louder, especially in // headphones. Above full scale a final limiter (a fast compressor) keeps loud // settings from clipping harshly; at normal levels it does nothing. One // volume is shared by every page. const VOLUME_MIN_DB = -50; const VOLUME_MAX_DB = 12; // a gain of 4 const VOLUME_DEFAULT_DB = -20; const AUDIO_FADE = 0.01; let audioCtx = null; let audioReady = null; let limiter = null; let audioVolume = (VOLUME_DEFAULT_DB - VOLUME_MIN_DB) / (VOLUME_MAX_DB - VOLUME_MIN_DB); const volumeGain = () => (audioVolume > 0 ? 10 ** ((VOLUME_MIN_DB + audioVolume * (VOLUME_MAX_DB - VOLUME_MIN_DB)) / 20) : 0); // the final limiter, shared by every sound function output(ctx) { if (!limiter) { limiter = ctx.createDynamicsCompressor(); limiter.threshold.value = -2; limiter.knee.value = 0; limiter.ratio.value = 20; limiter.attack.value = 0.002; limiter.release.value = 0.1; limiter.connect(ctx.destination); } return limiter; } function audioContext() { audioCtx ??= new AudioContext(); audioReady ??= audioCtx.audioWorklet.addModule('js/oscillator-worklet.js'); audioCtx.resume(); return audioReady.then(() => audioCtx); } // button (optional): Play / Stop. volume: a range input. params(): the // worklet's { omega2, alpha, delta, F, Omega, x0, ref } (see // oscillator-worklet.js). fftSize (optional): an analyser's window. // onPlay(analyser) and onStop() (optional) report the sound starting and // stopping; the analyser taps the sound before the volume, for the // spectrogram. play(start) starts the sound (or restarts it, if playing) from // start = { x, v, phase }, by default from rest at x0. route(ctx, node) // (optional, may be async) returns the node to send to the volume instead of // the oscillator's own, for processing the sound on the way. export function createSound({ button = null, volume, params, fftSize = 0, onPlay = () => {}, onStop = () => {}, route = null }) { let node = null; let gain = null; let starting = false; function stop() { starting = false; if (!node) return; const [n, g] = [node, gain]; g.gain.setTargetAtTime(0, audioCtx.currentTime, AUDIO_FADE / 3); setTimeout(() => { n.disconnect(); g.disconnect(); }, 100); node = null; gain = null; if (button) button.textContent = '\u266B Play'; onStop(); } async function play(start = {}) { if (node) { node.port.postMessage({ type: 'params', ...params() }); node.port.postMessage({ type: 'start', ...start }); return; } starting = true; if (button) button.textContent = '\u25A0 Stop'; const ctx = await audioContext(); if (!starting) return; // stopped while loading const osc = new AudioWorkletNode(ctx, 'oscillator-processor', { outputChannelCount: [1] }); const out = route ? await route(ctx, osc) : osc; if (!starting) return; // stopped while setting up starting = false; node = osc; gain = ctx.createGain(); gain.gain.value = volumeGain(); out.connect(gain).connect(output(ctx)); let analyser = null; if (fftSize) { analyser = ctx.createAnalyser(); analyser.fftSize = fftSize; analyser.smoothingTimeConstant = 0; node.connect(analyser); } node.port.onmessage = (e) => { if (e.data.type === 'ended') stop(); }; node.port.postMessage({ type: 'params', ...params() }); node.port.postMessage({ type: 'start', ...start }); onPlay(analyser); } button?.addEventListener('click', () => (node || starting ? stop() : play())); // changes apply while playing, smoothed over a few ms to avoid zipper noise volume.value = audioVolume; volume.addEventListener('input', () => { audioVolume = Number(volume.value); document.querySelectorAll('.volume input').forEach((other) => (other.value = audioVolume)); if (gain) gain.gain.setTargetAtTime(volumeGain(), audioCtx.currentTime, 0.01); }); return { play, stop, playing: () => Boolean(node || starting), // new parameters, applied to the playing sound update: () => node?.port.postMessage({ type: 'params', ...params() }), // new parameters, restarting the playing sound from rest at x0 restart: () => { node?.port.postMessage({ type: 'params', ...params() }); node?.port.postMessage({ type: 'start' }); }, }; }