/ interactive_tutorials / hardening_softening
Sign in
interactive_tutorials / hardening_softening
hardening_softening / app / js / sound.js
128 lines · 4.7 KBBlameHistoryRaw
1// Live sound of an oscillator: the motion is integrated on the audio thread
2// (oscillator-worklet.js), so it plays until stopped and follows parameter
3// changes as they happen.
4//
5// The worklet's output peaks at about 1 (at most 2, for a driven swing). The
6// volume slider (0 to 1) sets the gain in decibels, evenly from
7// VOLUME_MIN_DB to VOLUME_MAX_DB (0 is silent); the default, VOLUME_DEFAULT_DB,
8// gives a peak of 0.1, since a pure tone is harsh much louder, especially in
9// headphones. Above full scale a final limiter (a fast compressor) keeps loud
10// settings from clipping harshly; at normal levels it does nothing. One
11// volume is shared by every page.
13const VOLUME_MIN_DB = -50;
14const VOLUME_MAX_DB = 12; // a gain of 4
15const VOLUME_DEFAULT_DB = -20;
16const AUDIO_FADE = 0.01;
17let audioCtx = null;
18let audioReady = null;
19let limiter = null;
20let audioVolume = (VOLUME_DEFAULT_DB - VOLUME_MIN_DB) / (VOLUME_MAX_DB - VOLUME_MIN_DB);
21const volumeGain = () => (audioVolume > 0 ? 10 ** ((VOLUME_MIN_DB + audioVolume * (VOLUME_MAX_DB - VOLUME_MIN_DB)) / 20) : 0);
23// the final limiter, shared by every sound
24function output(ctx) {
25 if (!limiter) {
26 limiter = ctx.createDynamicsCompressor();
27 limiter.threshold.value = -2;
28 limiter.knee.value = 0;
29 limiter.ratio.value = 20;
30 limiter.attack.value = 0.002;
31 limiter.release.value = 0.1;
32 limiter.connect(ctx.destination);
33 }
34 return limiter;
37function audioContext() {
38 audioCtx ??= new AudioContext();
39 audioReady ??= audioCtx.audioWorklet.addModule('js/oscillator-worklet.js');
40 audioCtx.resume();
41 return audioReady.then(() => audioCtx);
44// button (optional): Play / Stop. volume: a range input. params(): the
45// worklet's { omega2, alpha, delta, F, Omega, x0, ref } (see
46// oscillator-worklet.js). fftSize (optional): an analyser's window.
47// onPlay(analyser) and onStop() (optional) report the sound starting and
48// stopping; the analyser taps the sound before the volume, for the
49// spectrogram. play(start) starts the sound (or restarts it, if playing) from
50// start = { x, v, phase }, by default from rest at x0. route(ctx, node)
51// (optional, may be async) returns the node to send to the volume instead of
52// the oscillator's own, for processing the sound on the way.
53export function createSound({ button = null, volume, params, fftSize = 0, onPlay = () => {}, onStop = () => {}, route = null }) {
54 let node = null;
55 let gain = null;
56 let starting = false;
58 function stop() {
59 starting = false;
60 if (!node) return;
61 const [n, g] = [node, gain];
62 g.gain.setTargetAtTime(0, audioCtx.currentTime, AUDIO_FADE / 3);
63 setTimeout(() => {
64 n.disconnect();
65 g.disconnect();
66 }, 100);
67 node = null;
68 gain = null;
69 if (button) button.textContent = '\u266B Play';
70 onStop();
71 }
73 async function play(start = {}) {
74 if (node) {
75 node.port.postMessage({ type: 'params', ...params() });
76 node.port.postMessage({ type: 'start', ...start });
77 return;
78 }
79 starting = true;
80 if (button) button.textContent = '\u25A0 Stop';
81 const ctx = await audioContext();
82 if (!starting) return; // stopped while loading
83 const osc = new AudioWorkletNode(ctx, 'oscillator-processor', { outputChannelCount: [1] });
84 const out = route ? await route(ctx, osc) : osc;
85 if (!starting) return; // stopped while setting up
86 starting = false;
87 node = osc;
88 gain = ctx.createGain();
89 gain.gain.value = volumeGain();
90 out.connect(gain).connect(output(ctx));
91 let analyser = null;
92 if (fftSize) {
93 analyser = ctx.createAnalyser();
94 analyser.fftSize = fftSize;
95 analyser.smoothingTimeConstant = 0;
96 node.connect(analyser);
97 }
98 node.port.onmessage = (e) => {
99 if (e.data.type === 'ended') stop();
100 };
101 node.port.postMessage({ type: 'params', ...params() });
102 node.port.postMessage({ type: 'start', ...start });
103 onPlay(analyser);
104 }
106 button?.addEventListener('click', () => (node || starting ? stop() : play()));
108 // changes apply while playing, smoothed over a few ms to avoid zipper noise
109 volume.value = audioVolume;
110 volume.addEventListener('input', () => {
111 audioVolume = Number(volume.value);
112 document.querySelectorAll('.volume input').forEach((other) => (other.value = audioVolume));
113 if (gain) gain.gain.setTargetAtTime(volumeGain(), audioCtx.currentTime, 0.01);
114 });
116 return {
117 play,
118 stop,
119 playing: () => Boolean(node || starting),
120 // new parameters, applied to the playing sound
121 update: () => node?.port.postMessage({ type: 'params', ...params() }),
122 // new parameters, restarting the playing sound from rest at x0
123 restart: () => {
124 node?.port.postMessage({ type: 'params', ...params() });
125 node?.port.postMessage({ type: 'start' });
126 },
127 };
↑↓ move↵openescclose