@margoengine/audio 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +987 -2
  4. package/dist/ambisonics.d.ts +54 -0
  5. package/dist/ambisonics.js +118 -0
  6. package/dist/analyser.d.ts +45 -0
  7. package/dist/audio.d.ts +282 -0
  8. package/dist/binaural.d.ts +35 -0
  9. package/dist/binaural.js +123 -0
  10. package/dist/doppler.d.ts +44 -0
  11. package/dist/doppler.js +82 -0
  12. package/dist/errors-D8rc8kzg.js +7 -0
  13. package/dist/events.d.ts +54 -0
  14. package/dist/events.js +78 -0
  15. package/dist/index.d.ts +12 -0
  16. package/dist/index.js +303 -0
  17. package/dist/listener.d.ts +116 -0
  18. package/dist/loader.d.ts +22 -0
  19. package/dist/math-C82bLsED.js +44 -0
  20. package/dist/math.d.ts +19 -0
  21. package/dist/music.d.ts +76 -0
  22. package/dist/music.js +106 -0
  23. package/dist/occlusion.d.ts +50 -0
  24. package/dist/occlusion.js +75 -0
  25. package/dist/outdoor.d.ts +37 -0
  26. package/dist/outdoor.js +52 -0
  27. package/dist/pan.d.ts +21 -0
  28. package/dist/pan.js +28 -0
  29. package/dist/rate-control-BiZ5FnNk.js +4 -0
  30. package/dist/rate-control.d.ts +5 -0
  31. package/dist/resample.d.ts +53 -0
  32. package/dist/resample.js +245 -0
  33. package/dist/scan.d.ts +66 -0
  34. package/dist/scan.js +75 -0
  35. package/dist/sinc-CbjImCBh.js +36 -0
  36. package/dist/sinc.d.ts +5 -0
  37. package/dist/spectrogram-fft-CRLetuHA.js +59 -0
  38. package/dist/spectrogram-fft.d.ts +26 -0
  39. package/dist/spectrogram-windows.d.ts +24 -0
  40. package/dist/spectrogram.d.ts +143 -0
  41. package/dist/spectrogram.js +384 -0
  42. package/dist/sprites.d.ts +59 -0
  43. package/dist/sprites.js +99 -0
  44. package/dist/stretch.d.ts +25 -0
  45. package/dist/stretch.js +55 -0
  46. package/dist/vocoder-envelope.d.ts +5 -0
  47. package/dist/vocoder-phase.d.ts +7 -0
  48. package/dist/vocoder-split.d.ts +10 -0
  49. package/dist/vocoder.d.ts +59 -0
  50. package/dist/vocoder.js +291 -0
  51. package/dist/voice-manager.d.ts +100 -0
  52. package/dist/voice-manager.js +178 -0
  53. package/dist/voices-CdfPmzIo.js +425 -0
  54. package/dist/voices.d.ts +45 -0
  55. package/dist/wav.d.ts +47 -0
  56. package/dist/wav.js +156 -0
  57. package/dist/zones.d.ts +43 -0
  58. package/dist/zones.js +75 -0
  59. package/package.json +130 -4
package/README.md CHANGED
@@ -1,3 +1,988 @@
1
- # Temporary Holding Version
1
+ # @margoengine/audio
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Web Audio listener, global and positional sounds and a frequency analyser for Margo Engine.
4
+
5
+ Pose writes read the three stored vector components directly. They preserve the existing parameter scheduling,
6
+ smoothing and clock-read order. This removes vector-iterator work; it does not establish a measured speedup.
7
+ For a self-contained offline example with no audio device or user gesture:
8
+
9
+ ```ts
10
+ import {AudioListener, PositionalAudio} from '@margoengine/audio';
11
+
12
+ const context = new OfflineAudioContext(2, 4800, 48000);
13
+ const listener = new AudioListener({context, autoResume: false, smoothing: 0});
14
+ const sound = new PositionalAudio(listener);
15
+ const oscillator = context.createOscillator();
16
+ sound.setNodeSource(oscillator);
17
+ sound.setPosition(1, 0, -2).setDirection([0, 0, 1]);
18
+ oscillator.start();
19
+ const rendered = await context.startRendering();
20
+ console.assert(rendered.length === 4800 && rendered.numberOfChannels === 2);
21
+ listener.dispose();
22
+ ```
23
+
24
+ Import `margoengine/audio` from the `margoengine` package, or `@margoengine/audio` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
25
+
26
+ Web Audio listener, global and positional sounds, encoded-file loading and a frequency analyser for Margo Engine.
27
+
28
+ Build from source with `npm run build` in `packages/audio`.
29
+
30
+ For the loading examples, serve `tests/fixtures/rain-foa.wav` at `/sounds/rain-foa.wav` (CC BY 4.0, attribution in `tests/fixtures/NOTICE.md`). Replace this shared sample with your app's engine, cue and step recordings.
31
+
32
+ ```ts
33
+ import {AudioListener, Audio, PositionalAudio, AudioVoicePool, AudioAnalyser} from 'margoengine/audio';
34
+ import {Engine} from 'margoengine/core';
35
+ import {createMesh} from 'margoengine/materials';
36
+ import {box} from 'margoengine/core';
37
+ const timeline = {seconds: 0, playing: true, speed: 1};
38
+ const meter = document.createElement('div');
39
+ const x = 0;
40
+ const y = 0;
41
+ const z = 0;
42
+ const engine = await Engine.create(document.querySelector('canvas')!);
43
+ const truck = engine.createMesh().setGeometry(box());
44
+
45
+ const listener = AudioListener.attach(engine, {volume: 0.8}); // follows engine.camera every frame; resumes on the first click or key press
46
+
47
+ const engineSound = new PositionalAudio(listener, {
48
+ mesh: truck, refDistance: 2, distanceModel: 'inverse', rolloffFactor: 1.2,
49
+ coneInnerAngle: 90, coneOuterAngle: 220, coneOuterGain: 0.3, muteWhenHidden: true,
50
+ });
51
+ engineSound.setBuffer(await listener.load('/sounds/rain-foa.wav'));
52
+ engineSound.loop = true;
53
+ engineSound.fadeIn(0.5);
54
+
55
+ const music = new Audio(listener, {volume: 0.4});
56
+ music.setMediaElementSource(document.querySelector('audio')!).play();
57
+
58
+ // A sound on an editor timeline: starts at timeline second 4, follows play, pause, scrubbing and timeline speed.
59
+ const cue = new Audio(listener, {volume: 0.6, loop: false, timelineStart: 4});
60
+ cue.setBuffer(await listener.load('/sounds/rain-foa.wav'));
61
+ engine.onFrame(() => cue.sync(timeline.seconds, timeline.playing, timeline.speed));
62
+
63
+ // Footsteps and block sounds: 6 voices share one buffer; a 7th overlapping play steals the oldest voice.
64
+ const steps = new AudioVoicePool(listener, await listener.load('/sounds/rain-foa.wav'), {voices: 6, refDistance: 2});
65
+ steps.play([x, y, z], {volume: 0.7, playbackRate: 0.9 + Math.random() * 0.2});
66
+
67
+ const analyser = new AudioAnalyser(music, 1024);
68
+ engine.onFrame(() => meter.style.width = `${analyser.getAverageFrequency() / 2.55}%`);
69
+
70
+ // On teardown (engine.dispose() does this too):
71
+ engine.removePlugin(listener.name);
72
+ ```
73
+
74
+ ## Cancel a load, and clean up with `using`
75
+
76
+ ```ts
77
+ import {AudioListener, Audio} from 'margoengine/audio';
78
+
79
+ using listener = new AudioListener({volume: 0.8}); // disposed at the end of the block
80
+ const buffer = await listener.load('/sounds/rain-foa.wav', {signal: AbortSignal.timeout(10_000)}); // rejects with an AbortError
81
+ using step = new Audio(listener).setBuffer(buffer);
82
+ step.play();
83
+ ```
84
+
85
+ Errors carry a stable `code` (`error.code`): `disposed` for a sound used after `dispose()`, `state` for `play()` before a source is set, `unsupported` when Web Audio or `fetch` is missing, `failed` for an HTTP or decoding failure. Each message says what to do.
86
+
87
+ ## How it works
88
+
89
+ - **Lazy context.** Nothing touches `AudioContext`, `window` or `document` at import time. The listener creates its `AudioContext` the first time `listener.context` is read (normally when the first sound is created), or uses the context you pass, for example an `OfflineAudioContext`. A context the listener created is closed on dispose; a context you passed is left open.
90
+ - **Listener follows the camera.** As an engine plugin the listener adds a frame pass (order 900) that runs after the camera and world matrices are updated. It writes the listener position, forward (camera position toward target) and camera up (including rolled and exact-pole views), and skips the write when nothing changed. `listener.follow(mesh, forward = [0, 0, 1], up = [0, 1, 0])` puts the ears on a mesh instead, such as a third-person character: its world position, its local `forward` axis (glTF characters face +Z) and its local `up` axis, read from the engine's world matrices each frame (a disposed mesh keeps the last pose). The listener always hands Web Audio an up at right angles to forward (the part of `up` across forward), so a top view with up +Y, `setPose(p, [0, -1, 0])` or `follow(rocket, [0, 1, 0])` keeps left and right: an up along forward becomes the up of that view pitched from level, `[0, 0, -1]` looking down and `[0, 0, 1]` looking up (in the mesh's own axes for `follow`). `follow('camera')` goes back; `follow(null)` stops following so only `setPose` moves the listener. `setPose` also sets the pose by hand when you do not use an engine.
91
+ - **Autoplay.** With `autoResume` (default) the listener resumes a suspended context on the first `pointerdown`, `mousedown`, `keydown` or `touchend` anywhere in the window, then removes its listeners. `suspend()` and `resume()` are there for explicit control.
92
+ - **Graph.** `source -> filters -> fade gain -> volume gain -> [PannerNode] -> master gain -> destination`. Fades have their own gain stage, so `fadeIn`/`fadeOut` never fight with `volume`, and hidden-mesh muting rides on the volume stage.
93
+ - **No clicks.** Volume, master volume, playback rate, detune, listener pose and panner pose move with `setTargetAtTime` (time constant `smoothing`, default 20 ms) on a running context. The first write, and every write on a suspended or offline context, is set immediately, so a sound never sweeps in from the origin.
94
+ - **Positional audio.** The panner reads its mesh's world matrix from `engineRuntime(engine).store.matrices` each frame: translation for position, the mesh's local `direction` axis (default +Z) for the cone. A disposed mesh keeps the last pose. With `muteWhenHidden` the sound fades out while the mesh or any ancestor is hidden.
95
+ - **Sources.** `setBuffer` (decoded files), `setMediaElementSource` (`<audio>`/`<video>`, one node per element and context, reused), `setMediaStreamSource` (microphone, WebRTC) and `setNodeSource` (oscillators, constant sources, worklets). Buffer sources keep a playhead across `pause`/`play`, including playback-rate changes and loop regions. `seek(seconds)` moves it whether playing, paused or stopped: a playing buffer restarts on one new source node (the old one is stopped and disconnected first, so they never overlap); looping wraps into the loop region; past the end of a non-looping buffer it clamps to the end and a playing sound ends (`onEnded` fires). Media elements seek through `currentTime`.
96
+ - **Timeline sync.** `sync(timelineSeconds, playing, rate = 1)`, called every frame with the editor's own clock, makes a buffer sound follow a timeline instead of the audio clock: silent before `timelineStart`, then at buffer position `offset + timelineSeconds - timelineStart` wrapped by the loop region, silent past the end of a non-looping sound. While playing it re-seeks only when the sound drifts more than `Audio.syncTolerance` (50 ms) from the timeline, so steady playback is never chopped and a seam crossing in a loop does not count as drift. With `playing` false (paused, scrubbing) it moves the playhead silently. `rate` is the timeline speed and sets `playbackRate`.
97
+ - **Voice pools.** `new AudioVoicePool(listener, buffer, {voices = 8, ...positional options})` makes `voices` positional sounds that share one decoded buffer, for sounds that overlap: footsteps, block breaks, hits. `play(position, {volume, playbackRate})` takes a voice that is not sounding, or when all are sounding steals the one that started longest ago (it is cut off at once); the play's `volume` and `playbackRate` (pitch variation) default to the pool's options, and a voice jumps to its new position and level instead of easing there. `play` returns the voice. `stopAll()` stops every voice; `dispose()` disposes them (the buffer stays usable).
98
+
99
+ Pool play validates all three finite position coordinates, finite playbackRate and
100
+ nonnegative finite volume before selecting or stopping a voice. Invalid inputs,
101
+ including sparse coordinate arrays, raise a linked RangeError and leave current playback intact.
102
+ - **Loading.** `loadAudioBuffer(context, url, {signal})` and `listener.load` share one download and one decoded buffer per context and URL. An aborted caller rejects with an `AbortError`; the download is cancelled once every waiting caller aborted. Failed loads are not cached.
103
+
104
+ ## API
105
+
106
+ | Export | Purpose |
107
+ | --- | --- |
108
+ | `AudioListener` | Engine plugin: lazy context, master gain (`input`, `volume`), `suspend`/`resume`, auto-resume, `load`, `follow` (camera, a mesh or nothing), `setPose`, `update` |
109
+ | `Audio` | Non-positional sound: `setBuffer`, `setMediaElementSource`, `setMediaStreamSource`, `setNodeSource`, `play(delay)`, `pause`, `stop(delay)`, `seek(seconds)`, `sync(timelineSeconds, playing, rate)`, `fadeIn`, `fadeOut`, `setFilters`, `loop`, `loopStart`, `loopEnd`, `playbackRate`, `detune`, `offset`, `duration`, `timelineStart`, `volume`, `currentTime`, `onEnded`, `getOutput`, readonly `isDisposed`; static `syncTolerance` |
110
+ | `PositionalAudio` | `Audio` plus a PannerNode: `attach(mesh)`, `setPosition`, `setDirection`, `setDirectionalCone`, `panningModel`, `distanceModel`, `refDistance`, `maxDistance`, `rolloffFactor`, `muteWhenHidden` |
111
+ | `AudioVoicePool` | `voices` positional sounds on one buffer: `play(position, {volume, playbackRate})` (free voice, else steals the oldest), `stopAll`, `dispose`, `voices` |
112
+ | `AudioAnalyser` | `getFrequencyData`, `getFloatFrequencyData`, `getWaveformData`, `getFloatWaveformData`, `getAverageFrequency`, `getDominantFrequency` |
113
+ | `loadAudioBuffer`, `clearAudioBufferCache`, `decodeAudio` | Cached fetch and decode with `AbortSignal` |
114
+ | `distanceGain`, `coneGain` | The PannerNode distance and cone formulas, for meters and tests |
115
+ | `smoothParam` | The click-free AudioParam setter the package uses |
116
+
117
+ ## Options
118
+
119
+ | Option | Applies to | Default |
120
+ | --- | --- | --- |
121
+ | `context` | listener | `new AudioContext()` on first use; pass a context or a factory |
122
+ | `volume` | listener, sounds | 1 |
123
+ | `autoResume` | listener | true |
124
+ | `smoothing` | listener (used by its sounds) | 0.02 s; 0 sets values immediately |
125
+ | `loop`, `loopStart`, `loopEnd` | sounds | false, 0, 0 (end of buffer: `loopStart: 2` alone loops from 2 s to the end in every browser; since 2026-11-15, as WebKit looped the whole buffer before) |
126
+ | `playbackRate`, `detune` | sounds | 1, 0 cents |
127
+ | `offset`, `duration` | sounds (buffers) | 0, whole buffer (ignored while looping) |
128
+ | `timelineStart` | sounds (buffers, with `sync`) | 0 s |
129
+ | `autoplay`, `filters`, `onEnded` | sounds | false, none, none |
130
+ | `panningModel` | positional | `'HRTF'` (or `'equalpower'`) |
131
+ | `distanceModel` | positional | `'inverse'` (or `'linear'`, `'exponential'`) |
132
+ | `refDistance`, `maxDistance`, `rolloffFactor` | positional | 1, 10000, 1 |
133
+ | `coneInnerAngle`, `coneOuterAngle`, `coneOuterGain` | positional | 360, 360, 0 |
134
+ | `mesh`, `direction`, `muteWhenHidden` | positional | none, +Z, false |
135
+ | `voices` | voice pool (which takes the positional options except `mesh`, `autoplay` and `filters`) | 8 |
136
+
137
+ ## Limits
138
+
139
+ - `fadeOut` on a buffer source schedules the stop on the audio clock and marks the sound stopped right away; media, stream and node sources stop through a timer.
140
+ - `stream` and `node` sources are gated by connecting and disconnecting them; starting an oscillator or constant source is up to you.
141
+ - The listener follows the camera or one mesh (`follow`); for anything else, `follow(null)` and call `setPose` yourself.
142
+ - `sync` is silent at a zero or negative (reverse) timeline rate: Web Audio cannot play a buffer backwards. It drives buffer sources only (it does nothing before `setBuffer`) and owns `play`, `pause` and `playbackRate` while you call it. A clip that ended on its own is not restarted within the last `syncTolerance` of its end.
143
+ - Browsers without `AudioListener.positionX` (older Firefox) fall back to `setPosition`/`setOrientation`, which cannot be smoothed.
144
+
145
+ ## Tests
146
+
147
+ `npm test` in `packages/audio` runs Node checks against a small fake Web Audio implementation: no context at import, lazy creation, camera following, mesh following with a local forward axis, first-write-immediate then smoothed automation, auto-resume, graph wiring with filters and panner, playhead math for pause, playback rate, offset, duration and loop regions, `seek` while playing (exactly one new source at the new offset), paused or stopped, `sync` (silent before `timelineStart`, no re-seek under the drift tolerance, one re-seek over it, silent scrubbing, loop wrapping without re-seeking at the seam, reverse is silent, sources released after many seeks), `onEnded` only on a natural end, fade ramps, mesh following and hidden-mesh muting, media, stream and node sources, analyser math, the distance and cone formulas, loader caching, abort and failure handling, dispose, and voice pools (overlapping plays on separate voices sharing the buffer, positions and per-play volume and rate applied at once, the oldest voice stolen, an ended voice reused first, `stopAll`, release on dispose). `npm run test:browser` (a browser script, not in CI) renders with `OfflineAudioContext` in Chromium: a source on the right is louder in the right channel (HRTF and equal-power), linear, inverse and exponential attenuation match the formulas within 2%, the cone drops to `coneOuterGain` behind the source, the analyser finds a 1 kHz tone, loop points, offset and duration pick the right samples, a seek while playing reads on from the new position on one source (and past the end ends it), fadeIn ramps linearly, and a voice pool plays two overlapping sounds at their own positions and volumes, steals its only voice for a second play and halves the length at playbackRate 2. A live WebGPU engine check confirms the listener follows the camera, the panner follows its mesh, hidden meshes go silent, a decoded WAV is cached, a media element reports `onEnded`, there are no WebGPU validation errors, and a real click resumes a suspended context. The script adds `--autoplay-policy=no-user-gesture-required`.
148
+
149
+ Apache-2.0 licensed.
150
+
151
+ ## Occlusion and obstruction
152
+
153
+ `@margoengine/audio/occlusion` traces scene geometry with the existing BVH raycaster.
154
+ Full cover muffles and lowers a positional sound; partial cover gives intermediate filtering.
155
+ The listener updates the controller after its sound poses, on WebGPU and both WebGL2 routes.
156
+ BVH loads only when `create` is called. Install the optional `@margoengine/bvh` peer when
157
+ using this entry alone; the audio root imports neither occlusion nor BVH.
158
+
159
+ ```ts
160
+ import {Engine, box} from 'margoengine/core';
161
+ import {AudioListener, PositionalAudio} from 'margoengine/audio';
162
+ import {AudioOcclusion} from 'margoengine/audio/occlusion';
163
+
164
+ const canvas = document.createElement('canvas');
165
+ document.body.append(canvas);
166
+ const engine = await Engine.create(canvas, {camera: {position: [0, 0, 4], target: [0, 0, 0]}});
167
+ const context = new OfflineAudioContext(2, 4800, 48000);
168
+ const listener = AudioListener.attach(engine, {context});
169
+ engine.createMesh().setGeometry(box()).setScale([4, 4, 0.1]).setPosition([0, 0, 2]);
170
+ using sound = new PositionalAudio(listener).setPosition(0, 0, 0);
171
+ const buffer = listener.context.createBuffer(1, 4800, 48000);
172
+ buffer.getChannelData(0).forEach((_, i, data) => { data[i] = 0.2 * Math.sin(2 * Math.PI * 1000 * i / 48000); });
173
+ sound.setBuffer(buffer);
174
+ using occlusion = await AudioOcclusion.create(sound, {signal: AbortSignal.timeout(10000)});
175
+ engine.render(); // updates listener and sound poses, then traces the wall
176
+ sound.play();
177
+ console.log(occlusion.blocked); // 1: all five rays hit the wall
178
+ const rendered = await context.startRendering(); // real muffled PCM without an autoplay gesture
179
+ console.log(rendered.length); // 4800 stereo frames
180
+ // In a live app, use the listener's default context and retain the objects until teardown.
181
+ engine.dispose();
182
+ ```
183
+
184
+ Options: `radius=0.25` m (0..100) samples the centre and four perpendicular source offsets;
185
+ 0 traces one ray. `blockedGain=0.25` (0..1), `blockedFrequency=800` Hz
186
+ (10..min(20000, Nyquist)), `smoothing=listener.smoothing` seconds (0..60),
187
+ `filter` includes all visible geometry by default, and `signal` defaults to none.
188
+ The source mesh and listener's followed mesh are excluded. Gain interpolates linearly with
189
+ blocked-ray fraction; cutoff interpolates geometrically from min(20000, Nyquist).
190
+ The 1 mm segment-end exclusion avoids endpoint self-intersections. Coincident positions are clear.
191
+ Owned `lowpass` and `attenuation` nodes append to the existing filter chain; ordinary volume,
192
+ fades and hidden muting stay independent. Keep that chain in place while active.
193
+ `dispose()` or `using` removes only these nodes; listener teardown also disposes controllers.
194
+ `update(engine)` runs explicitly after world matrices and sound/listener poses are current.
195
+ Without a live engine, updates retain the last blocked fraction and filter settings. Sound disposal detaches the controller before tracing; creating one on a disposed sound raises linked disposed. Explicit updates after controller disposal also raise linked disposed.
196
+
197
+ This is a sampled geometric approximation without diffraction, thickness/material transmission,
198
+ reflections or reverb-send control. BVH's visible CPU geometry coverage applies: fragment alpha
199
+ and arbitrary shader deformation are not evaluated; active skin/morph geometry needs a static
200
+ blocker/proxy. Radius is a sampled source aperture, not a physical acoustic simulation.
201
+ Node tests use stand-in rendering and audio graphs. The browser test measures generated tones
202
+ in real OfflineAudioContext renders beside real WebGPU, WebGL2 and compatibility engines.
203
+ Real recordings, listening quality, other browsers and speed are unmeasured.
204
+
205
+ ## Outdoor propagation
206
+
207
+ `OutdoorAudio` applies a solved outdoor path to a `PositionalAudio`. It uses a delay line, the 1 kHz gain,
208
+ and shelves driven by the 63 Hz and 8 kHz gains. The path model handles distance attenuation while the sound
209
+ continues to pan and use its authored volume and filters. `maxDelay` defaults to 30 seconds and accepts
210
+ values above zero through 180 seconds. Moving paths smooth with the listener's time constant unless you
211
+ pass `smoothing`. Use one time-of-flight controller per sound. The controller removes its nodes on disposal
212
+ and restores the sound's distance rolloff. Give the controller a finite delay and all eight finite octave gains.
213
+
214
+ ```ts
215
+ import { AudioListener, PositionalAudio } from 'margoengine/audio';
216
+ import { OutdoorAudio } from 'margoengine/audio/outdoor';
217
+ import { OutdoorSound } from 'margoengine/physics/outdoor-sound';
218
+ import { PhysicsWorld } from 'margoengine/physics/world';
219
+
220
+ const paths = new OutdoorSound();
221
+ const world = new PhysicsWorld({ rate: { num: 60, den: 1 } }).add(paths, {
222
+ links: [{ source: [0, 0, -34.3], listener: [0, 0, 0] }],
223
+ });
224
+ world.advance(1);
225
+ const audio = new OfflineAudioContext(2, 12000, 48000);
226
+ using listener = new AudioListener({ context: audio, smoothing: 0 });
227
+ using sound = new PositionalAudio(listener, { panningModel: 'equalpower' });
228
+ sound.setPosition(0, 0, -34.3);
229
+ using outdoor = new OutdoorAudio(sound, () => paths.read());
230
+ const pulse = audio.createBuffer(1, 64, 48000);
231
+ pulse.getChannelData(0)[0] = 1;
232
+ sound.setBuffer(pulse).play();
233
+ const pcm = (await audio.startRendering()).getChannelData(0);
234
+ console.log(pcm.findIndex((value) => Math.abs(value) > 1e-9) / 48000);
235
+ ```
236
+
237
+ ## Stereo panning
238
+
239
+ `StereoAudio` from `@margoengine/audio/pan` is a sound that is not placed in the world (music, a UI cue, a narrator
240
+ off to one side) with a left and right position. It is an `Audio` with everything that brings (buffers, media and
241
+ node sources, volume, fades, filters, `play`, `pause`, `using`), and a native `StereoPannerNode` after its volume.
242
+ The audio root does not import this entry.
243
+
244
+ ```ts
245
+ import {AudioListener} from 'margoengine/audio';
246
+ import {StereoAudio} from 'margoengine/audio/pan';
247
+
248
+ const context = new OfflineAudioContext(2, 4800, 48000);
249
+ using listener = new AudioListener({context, smoothing: 0});
250
+ using sound = new StereoAudio(listener, {pan: 0.5}); // halfway to the right
251
+ const tone = context.createConstantSource(); // a mono input of 1
252
+ sound.setNodeSource(tone);
253
+ tone.start();
254
+ const rendered = await context.startRendering();
255
+ const [left, right] = [rendered.getChannelData(0)[100], rendered.getChannelData(1)[100]];
256
+ console.log(left.toFixed(3), right.toFixed(3)); // 0.383 0.924: cos and sin of 3/8 pi
257
+ sound.pan = -1; // all the way left; smoothed by listener.smoothing on a running context
258
+ sound.panner.pan.linearRampToValueAtTime(1, context.currentTime + 2); // native automation, sample accurate
259
+ console.log(sound.pan); // -1: the getter keeps the last value set through `pan`, not the automation's
260
+ ```
261
+
262
+ - `pan` (option and property, default `0`) runs from -1 (left) to 1 (right). A value outside that range or not
263
+ finite throws a `RangeError` with MargoError code `state` and leaves the last value in place.
264
+ - Writes to `pan` move with `setTargetAtTime` at `listener.smoothing` (default 0.02 s) on a running context, so a
265
+ jump does not click; on a suspended or offline context, or with `smoothing: 0`, they are set at once, as for volume.
266
+ - `panner` is the native node. Its `pan` AudioParam takes any Web Audio automation (`setValueCurveAtTime`, ramps) or
267
+ an `OscillatorNode` connected to it for an auto-pan; the `pan` getter then reports the last value written through
268
+ the property, not what the automation is playing.
269
+ - The pan is the equal-power law of Web Audio. A mono input goes to both sides at cos and sin of `(pan + 1) / 4` pi
270
+ (0.707 each at 0). A stereo input is balanced instead: toward the left, the right channel is folded into the left;
271
+ toward the right, the other way; at 0 it passes unchanged. The node always gives two channels.
272
+ - The sound has no position, distance model or cone; use `PositionalAudio` for a sound in the world.
273
+ - `getOutput()` returns the panner, so analysers and wet sends hear the panned signal.
274
+ - A context without `createStereoPanner` refuses the sound before anything is made, with MargoError code
275
+ `unsupported`. `dispose()` (or `using`, or the listener's `dispose()`) stops the source and disconnects the panner;
276
+ it can be called again safely, and writing `pan` after it throws with code `disposed`.
277
+
278
+ Tests: `tests/pan.test.js` (graph, validation, smoothing, lifecycle, teardown and the unsupported context, on
279
+ stand-in audio) and `tests/pan-browser.js` (rendered channels in a real browser).
280
+
281
+ ## Sprite sheets and format fallbacks (`@margoengine/audio/sprites`)
282
+
283
+ An audio sprite sheet is one file holding many short sounds (UI clicks, coins, footsteps) one after another.
284
+ `AudioSpriteBank` names their intervals and plays any of them, overlapping, from the one decoded buffer: no slicing
285
+ and no copies. `loadAudioFallback` loads the first of several encodings that the browser can play.
286
+
287
+ ```ts
288
+ import {AudioListener} from 'margoengine/audio';
289
+ import {AudioSpriteBank, loadAudioFallback} from 'margoengine/audio/sprites';
290
+
291
+ const context = new OfflineAudioContext(2, 48000, 48000);
292
+ using listener = new AudioListener({context, smoothing: 0});
293
+ // Opus where the browser plays it, else the WAV; a URL that fails to load moves on to the next.
294
+ const buffer = await loadAudioFallback(listener, ['/sounds/rain-foa.opus', '/sounds/rain-foa.wav'], {
295
+ signal: AbortSignal.timeout(10000),
296
+ });
297
+ using bank = new AudioSpriteBank(listener, buffer, {
298
+ click: {offset: 0, duration: 0.05},
299
+ coin: {offset: 0.1, duration: 0.25},
300
+ hum: {offset: 0.5, duration: 0.4, loop: true}, // loops inside its own interval
301
+ });
302
+ console.log(bank.names); // ['click', 'coin', 'hum']
303
+ bank.play('coin'); // fire and forget: released when it ends
304
+ bank.play('coin', {volume: 0.5, playbackRate: 1.2}, 0.05); // overlaps the first, 50 ms later on the audio clock
305
+ const hum = bank.create('hum', {volume: 0.3}).play(); // yours to stop, play again or dispose
306
+ console.log((await context.startRendering()).length); // 48000
307
+ hum.stop();
308
+ ```
309
+
310
+ - **Sprites.** Each entry is `{offset, duration, loop?}` in buffer seconds: `offset` 0 or more, `duration` above 0,
311
+ the whole interval inside the buffer, `loop` default `false`. Names are any nonempty strings; `names` lists them
312
+ in the order given. A bad entry throws a `RangeError` with code `state` when the bank is made, and a buffer of no
313
+ length is refused.
314
+ - **`play(name, options, delay)`** starts a new `Audio` on the sprite's interval, `delay` seconds from now on the
315
+ audio clock (default 0), and returns it. Any number can overlap. The bank releases it when it ends; if you
316
+ `stop()` one yourself, dispose it too. `options` are the usual sound options (`volume`, `playbackRate`,
317
+ `detune`, `filters`, `onEnded`...) except the interval and loop ones, which belong to the sprite.
318
+ - **`create(name, options)`** makes the same sound stopped and gives it to you: play it again after it ends, stop
319
+ it, dispose it. A looping sprite repeats only its own interval.
320
+ - `stopAll()` stops everything: `play` sounds are released, `create` sounds stay yours and can play again. The
321
+ bank's `dispose()` (or `using`, or the listener's) disposes every sound it made; the buffer stays usable. An
322
+ unknown name throws code `state`; any call after disposal, code `disposed`.
323
+ - **`loadAudioFallback(listener, candidates, options)`** goes through `candidates` in order. A string's type comes
324
+ from its extension (`mp3`, `ogg`, `opus`, `wav`, `m4a`, `mp4`, `aac`, `webm`, `flac`); a URL without one needs
325
+ `{url, type}` with a MIME type, codecs included (`'audio/ogg; codecs="opus"'`). It skips each type the browser's
326
+ `canPlayType` answers `''` to, and loads the first that loads and decodes, with `listener.load` (cached, so a
327
+ second call returns the same buffer). A failed candidate moves on to the next. When none is playable it throws
328
+ code `unsupported`; when every playable one failed, code `failed` with an `AggregateError` of each failure as
329
+ its `cause`. `signal` stops the whole search. In a worker or a test there is no `document`: pass
330
+ `canPlayType(type)`.
331
+
332
+ ## One voice limit for every sound (`@margoengine/audio/voices`)
333
+
334
+ A voice pool caps the copies of one buffer. `AudioVoiceManager` caps every sound on a listener together: at most
335
+ `maxVoices` buffer sources play at once, chosen by priority, then by how loud each would be where the listener is.
336
+ The rest play on as virtual voices, with no source node but a clock that keeps running, so a sound that comes back
337
+ into the cap starts at the point it would have reached, not from the top.
338
+
339
+ ```ts
340
+ import {Audio, AudioListener, PositionalAudio} from 'margoengine/audio';
341
+ import {AudioVoiceManager} from 'margoengine/audio/voices';
342
+
343
+ const context = new OfflineAudioContext(2, 48000, 48000);
344
+ using listener = new AudioListener({context, smoothing: 0});
345
+ const buffer = context.createBuffer(1, 48000, 48000); // your decoded loop
346
+ using voices = new AudioVoiceManager(listener, {maxVoices: 2});
347
+
348
+ const music = voices.add(new Audio(listener, {loop: true}).setBuffer(buffer), {priority: 10}); // always heard
349
+ const near = voices.add(new PositionalAudio(listener, {loop: true}).setBuffer(buffer).setPosition(0, 0, -2));
350
+ const far = voices.add(new PositionalAudio(listener, {loop: true}).setBuffer(buffer).setPosition(0, 0, -200));
351
+ for (const voice of [music, near, far]) voice.play(); // play through the handles, not the sounds
352
+ console.log(voices.activeCount, voices.virtualCount, far.isVirtual); // 2 1 true: the far one is the quietest
353
+ far.playbackRate = 1.25; // pitch on the handle; its virtual clock runs 1.25 times as fast too
354
+ console.log((await context.startRendering()).length); // 48000
355
+ ```
356
+
357
+ - **`add(sound, {priority, gain})`** registers a sound that has a decoded buffer and the manager's listener
358
+ (`Audio`, `PositionalAudio`, `StereoAudio` or a pool's voice) and returns its handle. You keep the sound: the
359
+ manager never disposes it. A sound can be in one manager once (`attached` error); a sound with a media, stream or
360
+ node source, no buffer or another listener is refused with `unsupported`.
361
+ - **The handle is the transport.** `play`, `pause`, `stop`, `seek(seconds)`, `currentTime`, `isPlaying`,
362
+ `isVirtual`, `playbackRate`, `detune` and `priority` belong to the handle, which counts the virtual phase,
363
+ loop region and pitch included, and ends a one-shot on time (firing the sound's `onEnded`) even while it is
364
+ virtual. Calling the sound's own `play`, `pause`, `seek` or pitch setters behind the handle's back is not tracked:
365
+ the next re-rank puts the source back where the handle says. Volume, fades, filters, position and cone stay on the
366
+ sound and count in the ranking.
367
+ - **Ranking.** Higher `priority` (default 0, any finite number) always wins; among equals the louder estimate wins:
368
+ the sound's volume and fade times the listener's volume, times the distance and cone gain for a positional sound,
369
+ times `gain()` if you pass one (your occlusion or bus level, a nonnegative number; nothing in the graph changes). A
370
+ voice at or below `threshold` (default 0.0001) is virtual even with room under the cap. `maxVoices` (default 32;
371
+ 0 makes every voice virtual) and `threshold` can change live and re-rank at once.
372
+ - **When it re-ranks.** On every listener update (each frame when the listener follows a camera), on `add`, and on
373
+ any handle call. Losers stop before winners start, so the cap is never passed even for a moment.
374
+ - `activeCount` is the sources playing now and `virtualCount` the voices playing without one.
375
+ - **Disposal.** A handle's `dispose()` stops and unregisters its sound; the manager's `dispose()` (or `using`, or the
376
+ listener's) does that for all of them. The manager's own `dispose()` leaves the sounds and buffers to you (the listener's
377
+ disposes its sounds as always). A call on a disposed handle or manager
378
+ throws code `disposed`; a bad number throws a `RangeError` with code `state`.
379
+
380
+ ## Doppler
381
+
382
+ `@margoengine/audio/doppler` shifts buffer pitch from source and listener world motion.
383
+ Attach it after setting the buffer; the listener samples both poses after the sound update.
384
+ It works identically with WebGPU, native WebGL2 and WebGL2 compatibility rendering.
385
+ The audio root does not import this entry.
386
+
387
+ ```ts
388
+ import {AudioListener, PositionalAudio} from 'margoengine/audio';
389
+ import {AudioDoppler} from 'margoengine/audio/doppler';
390
+
391
+ const context = new OfflineAudioContext(2, 24000, 48000);
392
+ using listener = new AudioListener({context, smoothing: 0});
393
+ listener.follow(null);
394
+ using sound = new PositionalAudio(listener, {rolloffFactor: 0});
395
+ const buffer = context.createBuffer(1, 48000, 48000);
396
+ buffer.getChannelData(0).forEach((_, i, a) => { a[i] = 0.2 * Math.sin(2 * Math.PI * 1000 * i / 48000); });
397
+ sound.setBuffer(buffer).setPosition(20, 0, 0).play();
398
+ using doppler = new AudioDoppler(sound);
399
+ listener.update();
400
+ const paused = context.suspend(0.128);
401
+ const rendered = context.startRendering();
402
+ await paused;
403
+ sound.setPosition(20 - 34.3 * context.currentTime, 0, 0);
404
+ listener.update();
405
+ console.log(doppler.ratio); // 1.111...: source approaching at 34.3 m/s
406
+ sound.playbackRate = 1.1; // authored pitch, composed with Doppler (also works on pooled voices)
407
+ console.log(doppler.playbackRate, sound.isDisposed); // 1.1, false
408
+ await context.resume();
409
+ console.log((await rendered).length); // 24000 frames, shifted tone after the motion sample
410
+ ```
411
+
412
+ Options: `speedOfSound=343` m/s (finite, positive), `playbackRate=sound.playbackRate`
413
+ (finite, nonnegative, at most float32 maximum / 39). `doppler.playbackRate` reports authored pitch; `ratio` reports the motion multiplier. Writes to either `doppler.playbackRate` or `sound.playbackRate`, including pool/event per-play pitch, set authored pitch and compose with the current multiplier. The sound getter reports the effective rate. Controlled pools validate authored rates before stopping or stealing a voice. Disposal restores the last authored pitch. Detune,
414
+ volume, fades, filters and the panner stay independent. Use one controller per sound;
415
+ duplicate attachment raises `attached`. Buffer sources only; other source kinds raise
416
+ `unsupported` on attachment, with a help link. Switching an attached sound to media, stream or node sources detaches Doppler on the next listener update and restores authored pitch without interrupting other sources.
417
+
418
+ Live contexts estimate velocity with monotonic `performance.now()` frame time, independently of device-clock quantization. Offline contexts use their exact audio clock. Initial, coincident and backward-clock samples are neutral; repeated sample times retain history. Live suspension/resume state changes clear history automatically, including autoplay unlock. A live render gap over 0.25 s or displacement speed over 0.95 times speedOfSound is a discontinuity and produces a neutral sample. Smaller teleports are indistinguishable from real motion: call `reset()` before the next update after those cuts. Explicit `update()` needs current sound/listener poses;
419
+ attached listeners do this automatically. Updates use existing playback-rate smoothing
420
+ (`listener.smoothing=0.02` s by default). Playback speed and duration change with pitch.
421
+ Do not combine with `Audio.sync`, which also owns playback rate.
422
+
423
+ The classical stationary-medium ratio is `(c + listener radial velocity) / (c + source
424
+ radial velocity)` with the axis pointing listener to source. Each radial Mach number
425
+ is clamped to -0.95..0.95, bounding the ratio to 1/39..39. This keeps extreme motion
426
+ finite; supersonic propagation, sonic booms, wind, travel delay and retarded positions
427
+ are outside this instantaneous approximation. Stop updating to freeze the last pitch;
428
+ dispose or reset to restore it. Sound disposal detaches on the next listener update;
429
+ listener teardown disposes controllers. Supports `using` and idempotent `dispose()`.
430
+ Node tests use stand-in audio. Real browser renders measure generated 1 kHz tones for
431
+ approach, recession, listener approach, co-motion and rest on all three rendering routes.
432
+ Generated audio/motion are stand-ins; recordings, listening quality, other browsers
433
+ and performance remain unmeasured.
434
+
435
+ ## Sound event containers
436
+
437
+ `@margoengine/audio/events` selects decoded one-shots in random or sequence order,
438
+ with independent pitch and volume variation and an audio-clock cooldown. It reuses
439
+ `AudioVoicePool`; the audio root does not import it. WebGPU and both WebGL2 routes
440
+ use the same Web Audio graph.
441
+
442
+ ```ts
443
+ import {AudioListener} from 'margoengine/audio';
444
+ import {AudioEventContainer} from 'margoengine/audio/events';
445
+
446
+ const context = new OfflineAudioContext(2, 14400, 48000);
447
+ using listener = new AudioListener({context});
448
+ const buffers = [600, 900].map(hz => {
449
+ const buffer = context.createBuffer(1, 3840, 48000);
450
+ buffer.getChannelData(0).forEach((_, i, a) => { a[i] = 0.2 * Math.sin(2 * Math.PI * hz * i / 48000); });
451
+ return buffer;
452
+ });
453
+ using footsteps = new AudioEventContainer(listener, buffers, {
454
+ mode: 'sequence', volume: [0.5, 0.8], pitch: [-50, 50], cooldown: 0.1,
455
+ });
456
+ footsteps.play([0, 0, -1]);
457
+ console.log(footsteps.play([0, 0, -1])); // null: cooldown does not consume a sequence step
458
+ const paused = context.suspend(0.128);
459
+ const rendered = context.startRendering();
460
+ await paused;
461
+ footsteps.play([0, 0, -1]); // second buffer
462
+ await context.resume();
463
+ console.log((await rendered).length); // 14400 frames
464
+ // In a live game, load buffers with listener.load(url, {signal}) and call play on game events.
465
+ ```
466
+
467
+ `AudioEventContainer(listener, buffers, options)` needs a nonempty list of decoded,
468
+ positive-duration buffers. `mode='random'` chooses uniformly, excluding the previous
469
+ buffer index when there is more than one; `'sequence'` visits indices in order and
470
+ wraps. Repeated buffer objects at different indices remain separate choices.
471
+ `voices=4` preallocates that many voices per buffer; a full pool steals its oldest
472
+ voice. Total voices are buffer count times `voices`; there is no global container
473
+ voice limit. Returned voices can be moved or stopped while they play.
474
+
475
+ `volume=[1,1]` is a uniform linear gain range within 0..1. `pitch=[0,0]` is a uniform
476
+ cents range within -4800..4800, converted to playbackRate with `2 ** (cents / 1200)`;
477
+ pitch also changes duration. Endpoints are snapshotted, finite and ordered. `cooldown=0`
478
+ is a finite nonnegative interval in audio-clock seconds. A rejected play returns null
479
+ without consuming random draws or sequence state. Context suspension freezes cooldown;
480
+ a backwards clock accepts a new play and starts a new interval. Play positions default
481
+ to `[0,0,0]` in metres. Invalid positions or draws fail before stopping an existing voice.
482
+
483
+ `random=Math.random` can be replaced with a uniform function returning a finite number
484
+ in `[0,1)` for reproducible runs. Constant ranges and a single-buffer selection need
485
+ no draw. Draw order is selection (random mode with multiple buffers), volume, pitch.
486
+ `voiceOptions` defaults to the pool's spatial and clip defaults; looping, voice count,
487
+ volume, detune and playback rate are controlled by the container. No buffer is cloned
488
+ or loaded here; existing listener loading supports AbortSignal. No timers or waiting.
489
+ `lastIndex=-1` until the first accepted play; `stopAll()` retains history/cooldown.
490
+ `dispose()` and `using` release voices, preserve shared buffers and are idempotent;
491
+ listener teardown also disposes the container. Disposed use raises `disposed` with a
492
+ help link; invalid selections use `state` and invalid ranges use linked RangeError.
493
+
494
+ Node tests cover order, variation, exact cooldown boundaries, deterministic selection,
495
+ single-buffer play, overlap, stealing, teardown and failure atomicity. Real browser
496
+ PCM measures generated sequence/random tones and a silent cooldown gap beside WebGPU,
497
+ native WebGL2 and compatibility WebGL2. Generated audio/events are stand-ins; real
498
+ recordings, listening quality, other browsers and performance are unmeasured.
499
+
500
+ ## Adaptive music
501
+
502
+ `@margoengine/audio/music` starts decoded stems together and changes their levels on
503
+ beat or bar boundaries. Install the optional peer `@margoengine/mixer` alongside audio;
504
+ the entry reuses mixer buses and audio-clock gain scheduling. WebGPU, native WebGL2
505
+ and compatibility WebGL2 share the same Web Audio graph.
506
+
507
+ ```ts
508
+ import {AudioListener} from 'margoengine/audio';
509
+ import {AudioMusic} from 'margoengine/audio/music';
510
+
511
+ const context = new OfflineAudioContext(2, 72000, 48000);
512
+ using listener = new AudioListener({context});
513
+ const tone = (hz: number) => {
514
+ const buffer = context.createBuffer(1, 24000, 48000);
515
+ buffer.getChannelData(0).forEach((_, i, a) => { a[i] = 0.1 * Math.sin(2 * Math.PI * hz * i / 48000); });
516
+ return buffer;
517
+ };
518
+ using music = new AudioMusic(listener, {base: tone(600), drums: tone(900)}, {
519
+ explore: {base: -6}, combat: {base: -6, drums: -6},
520
+ }, {loopBeats: 1, leadTime: 0});
521
+ music.start('explore', 0);
522
+ console.log(music.transition('combat', {quantize: 'beat', after: 0.1})); // 0.5 seconds
523
+ console.log((await context.startRendering()).length); // 72000 frames
524
+ ```
525
+
526
+ In a game, use `listener.load(url, {signal})` for authored stems and call
527
+ `transition('combat')` when game state changes. States map stem names to dB levels;
528
+ omitted stems and `-Infinity` are silent. States are copied at construction. Gains
529
+ must fit finite float32 linear values. This is gain layering of continuously running
530
+ loops: muted stems keep their phase. Every loop is its own source started at
531
+ `origin + k * loop` on the audio clock, so a browser that rounds start or loop points to
532
+ whole frames (Firefox) never drifts off the grid. An `OfflineAudioContext` render (a soundtrack bounce)
533
+ is scheduled a window of loops at a time and refilled at `suspend(time)` points, because every scheduled source costs
534
+ the renderer work on each render quantum until it ends: an hour at 130 bpm renders in under a second in Chromium
535
+ instead of 35 s. A browser without `suspend(time)` on offline contexts (Firefox), or an app that already holds a
536
+ suspend at the same render quantum, gets the whole render scheduled at once: the same samples, rendered more slowly.
537
+ No tempo analysis, stretching, sequencing of
538
+ different sections, streaming, or automatic loudness/headroom management.
539
+
540
+ Options: `bpm=120` positive finite quarter-note beats/minute, `beatsPerBar=4` and
541
+ `loopBeats=4` positive integers, `leadTime=0.05` finite nonnegative scheduling seconds,
542
+ `fade=0.02` finite nonnegative mixer exponential fade seconds (about 98% settled;
543
+ 0 jumps). Each decoded buffer must cover `loopBeats * 60 / bpm` seconds. Only that
544
+ interval loops; trailing samples are unused. Author seamless, aligned stems; buffers
545
+ are shared. Tempo and loop length stay fixed for a transport.
546
+
547
+ `start(state, at=currentTime+leadTime)` requires a stopped transport and a finite
548
+ time at/after now; returns the common origin. `transition(state, {quantize='bar',
549
+ after=currentTime, fade=constructor default})` returns the first grid time at/after
550
+ both `after` and `currentTime+leadTime`, relative to that origin. Exact boundaries
551
+ are eligible. Schedule ahead of time for live playback; a main-thread call that
552
+ arrives late moves to the next eligible boundary. Audio-clock suspension freezes
553
+ the grid. No timers or frame scheduling. A new request replaces mixer automation
554
+ at/after its chosen boundary, preserving earlier transitions; fades are exponential,
555
+ not equal-power crossfades. Validate requests before changing playback.
556
+
557
+ `stop()` cuts sources immediately, including future starts. Restart resets phase and
558
+ pending automation. `dispose()`, `using`, and listener teardown release owned sources
559
+ and mixer buses, preserving buffers. Disposed use raises linked `disposed`; invalid
560
+ states/grid use linked `state` errors. No core/stage changes. Node stand-ins cover
561
+ scheduling and lifecycle; real browser generated-stem PCM checks phase, loop, layering
562
+ and beat/bar boundaries on all three routes. Recordings, listening quality, other
563
+ browsers and performance remain unmeasured.
564
+
565
+ ## Reverb zones
566
+
567
+ `@margoengine/audio/zones` selects a room response as the listener moves through
568
+ axis-aligned areas. It reuses `@margoengine/mixer/reflections` and mixer automation;
569
+ install the optional `@margoengine/mixer` peer alongside audio. WebGPU and both
570
+ WebGL2 routes use the same Web Audio convolution graph.
571
+
572
+ ```ts
573
+ import {AudioListener, Audio} from 'margoengine/audio';
574
+ import {AudioReverbZones} from 'margoengine/audio/zones';
575
+
576
+ const context = new OfflineAudioContext(2, 24000, 48000);
577
+ using listener = new AudioListener({context});
578
+ using zones = new AudioReverbZones(listener, [
579
+ {name: 'hall', min: [-4, -2, -4], max: [4, 2, 4],
580
+ reverb: {room: [8, 4, 8], seconds: 0.2}},
581
+ ]);
582
+ const buffer = context.createBuffer(1, 4800, 48000);
583
+ buffer.getChannelData(0)[0] = 0.25;
584
+ using sound = new Audio(listener).setBuffer(buffer);
585
+ sound.getOutput().connect(zones.input); // additional wet send; the dry route already exists
586
+ sound.play();
587
+ console.log(zones.active); // hall
588
+ console.log((await context.startRendering()).length); // 24000 frames
589
+ sound.getOutput().disconnect(zones.input);
590
+ ```
591
+
592
+ `AudioReverbZones(listener, zones, {fade=0.1})` copies finite ordered `min`/`max`
593
+ world bounds in metres. Names must be unique and nonempty. Bounds are inclusive;
594
+ o matching zone means a silent wet send. Greatest finite `priority=0` wins overlap;
595
+ equal priorities select the first listed zone. `gain=0.25` is linear wet-send gain
596
+ in 0..1, added to the unchanged dry route. Manage headroom for combined dry/wet audio.
597
+ `reverb={}` takes the existing [mixer room settings and defaults](../mixer/README.md#early-room-reflections),
598
+ with `mix` always 1 for wet-only output. Bounds select a response; they do not define
599
+ the response's room geometry or move its authored source/listener positions.
600
+
601
+ `fade=0.1` is finite nonnegative mixer exponential fade seconds (about 98% settled);
602
+ 0 jumps. One convolution and response buffer per zone are prepared at construction.
603
+ Only selection/send gains change on movement. Old tails ring out after a switch or
604
+ exit; the input feed fades, preserving convolution state. Resource cost grows with
605
+ zone count and room response length; this is an authored zone model, without
606
+ continuous propagation, portals, diffraction or automatic room geometry analysis.
607
+
608
+ `active` reports the selected name or null. Attached listeners update selection each
609
+ frame after their pose; otherwise call `listener.update()` or `zones.update()` after
610
+ setting the listener pose. Selection follows game frames, fades follow the audio
611
+ clock. Unchanged selection schedules nothing. Empty zone lists are valid wet silence.
612
+ No loading, waits or timers. Listener loading already supports AbortSignal.
613
+
614
+ `dispose()`, `using` and listener teardown disconnect owned sends/effects immediately,
615
+ cutting tails. If a manually connected source will outlive the controller, disconnect
616
+ its connection into `zones.input`. Shared source dry routes stay independent. Disposed
617
+ updates raise linked `disposed`; invalid bounds/names/levels raise linked `state`.
618
+ Room settings use the mixer's validation. Node tests cover priority, boundaries,
619
+ immutable bounds, teardown and failure cleanup. Real browser PCM compares generated
620
+ impulses to existing mixer responses across room entry/switch/exit, including dry
621
+ sound and retained tails, on all three routes. Generated rooms/motion are stand-ins;
622
+ recordings, listening quality, other browsers and performance remain unmeasured.
623
+
624
+ ## Ambisonic beds
625
+
626
+ `@margoengine/audio/ambisonics` plays and rotates first-order AmbiX beds (four
627
+ ACN/SN3D channels W,Y,Z,X). It uses Web Audio splitters, a rotation/decoder gain
628
+ matrix and a stereo merger on WebGPU, native WebGL2 and compatibility WebGL2.
629
+
630
+ ```ts
631
+ import {AudioListener} from 'margoengine/audio';
632
+ import {AmbisonicAudio} from 'margoengine/audio/ambisonics';
633
+
634
+ const context = new OfflineAudioContext(2, 24000, 48000);
635
+ using listener = new AudioListener({context, smoothing: 0});
636
+ const buffer = context.createBuffer(4, 24000, 48000);
637
+ // A generated plane-wave tone from the recording's front: W = X, Y = Z = 0.
638
+ for (let i = 0; i < buffer.length; i++) {
639
+ const sample = 0.1 * Math.sin(2 * Math.PI * 600 * i / 48000);
640
+ buffer.getChannelData(0)[i] = sample;
641
+ buffer.getChannelData(3)[i] = sample;
642
+ }
643
+ using bed = new AmbisonicAudio(listener, buffer, {volume: 0.5});
644
+ bed.setRotation([0, Math.SQRT1_2, 0, Math.SQRT1_2]).play(); // 90-degree world Y rotation
645
+ console.log((await context.startRendering()).length); // 24000 frames
646
+ ```
647
+
648
+ For a file, use `await listener.load(url, {signal})`, then construct the bed from
649
+ that decoded buffer. Four-channel PCM WAV is tested. Browser codec/container support
650
+ controls loading; this entry does not parse CAF adaptor matrices, Opus mapping
651
+ metadata or infer normalization from a buffer. Confirm ACN/SN3D before passing it.
652
+ `format='ambix'` is the only supported convention. FuMa, N3D, A-format, higher orders,
653
+ extra stereo channels and mixed-order layouts need conversion first; other formats
654
+ or channel counts raise `unsupported` with a help link. Buffers have positive finite
655
+ duration and are shared. No core/stage changes or additional peer dependencies.
656
+
657
+ The decoder uses two virtual cardioid microphones at +/-30 degrees about listener
658
+ forward: each output is `0.5 * (W + dot(direction, [X,Y,Z]))`, then output volume.
659
+ This gives orientation-dependent stereo ambience. It is not an HRTF/binaural decoder,
660
+ loudspeaker-layout decoder or a guarantee of headphone front/back/elevation localization.
661
+ ACN axes are X front, Y left, Z up. Identity field orientation maps those to engine
662
+ world -Z, -X, +Y respectively. `setRotation([x,y,z,w])` applies an active world-space
663
+ field rotation, normalized and copied. Listener orientation applies the inverse head
664
+ rotation to the bed. Translation is ignored for this infinitely distant ambience.
665
+
666
+ `loop=true` loops the complete buffer; `volume=1` is linear gain in 0..1; `smoothing`
667
+ defaults to `listener.smoothing` (0.02 s), a finite nonnegative time constant, with
668
+ 0 immediate. Independent channel gains interpolate during orientation changes;
669
+ intermediate matrices during a fade are a blend, not an exact rigid rotation.
670
+ Use aligned/seamless loops and manage headroom. Eight gain paths and one source per
671
+ bed; no convolution, worklet, per-sample JavaScript or HRTF assets. Unchanged matrices
672
+ schedule nothing. `volume` can be changed independently of field rotation.
673
+
674
+ `play(at=context.currentTime)` starts from phase zero at/after now; a playing or
675
+ scheduled bed must be stopped before restart. `isPlaying` includes scheduled starts.
676
+ Natural end clears it for `loop=false`. `stop()` cuts and disconnects playback.
677
+ `dispose()`, `using` and listener teardown release decoder nodes and preserve buffers.
678
+ Disposed calls raise linked `disposed`; invalid values use linked `state` errors.
679
+
680
+ The listener updates the matrix each frame. For XR, feed the headset's world forward
681
+ and up vectors through `listener.follow(null).setPose(position, forward, up)` before
682
+ `listener.update()`. A collinear pose keeps the last independent decoder orientation; a bed created at such a pose starts facing -Z with +Y up. A valid pose resumes orientation updates.
683
+ This entry adds no XR session/headset driver. Physical headset tracking and subjective
684
+ localization are unmeasured. CPU tests cover full quaternion yaw/pitch/roll basis
685
+ changes; browser PCM covers channel routing, looping, listener yaw and field yaw on
686
+ all three routes. Evidence uses generated independent tones and a licensed external
687
+ rain stimulus excerpt: [source/changes](tests/fixtures/NOTICE.md). That file validates
688
+ decoding/resampling and matrix output, not a microphone chain or recording provenance.
689
+ Listening quality, other browsers/devices and performance remain unmeasured.
690
+
691
+ ### Binaural beds, orders 1 to 3 (`@margoengine/audio/binaural`)
692
+
693
+ `BinauralAudio` plays an AmbiX bed of first, second or third order (4, 9 or 16 ACN/SN3D channels) over headphones
694
+ through the browser's own HRTFs. The bed is decoded onto 32 virtual loudspeakers on a Gauss-Legendre sphere (four
695
+ rings of eight), each a native `PannerNode` with `panningModel: 'HRTF'`, so front, back and height cues come from the
696
+ browser rather than from the two cardioids of `AmbisonicAudio`. The audio root does not import this entry.
697
+
698
+ ```ts
699
+ import {AudioListener} from 'margoengine/audio';
700
+ import {BinauralAudio, ambixBasis} from 'margoengine/audio/binaural';
701
+
702
+ const context = new OfflineAudioContext(2, 12288, 48000);
703
+ using listener = new AudioListener({context, smoothing: 0});
704
+ listener.follow(null).setPose([0, 0, 0], [0, 0, -1]); // facing -Z, the bed's front
705
+ // A second-order plane wave from the bed's left ([front, left, up] = [0, 1, 0]): each channel is the tone times its harmonic.
706
+ const gains = ambixBasis(2, [0, 1, 0]);
707
+ const buffer = context.createBuffer(gains.length, 12288, 48000);
708
+ for (let c = 0; c < gains.length; c++)
709
+ buffer.getChannelData(c).forEach((_, i, a) => { a[i] = 0.1 * gains[c] * Math.sin(2 * Math.PI * 500 * i / 48000); });
710
+ using bed = new BinauralAudio(listener, buffer); // loops by default
711
+ console.log(bed.order, bed.speakerCount); // 2 32
712
+ bed.setRotation([0, Math.SQRT1_2, 0, Math.SQRT1_2]).play(); // turn the field 90 degrees about world Y
713
+ const out = await context.startRendering();
714
+ console.log(out.numberOfChannels, out.length); // 2 12288
715
+ ```
716
+
717
+ - **Input.** AmbiX only (`format: 'ambix'`, the default): ACN channel order with SN3D normalisation, the layout
718
+ YouTube spatial audio and most ambisonic plug-ins use. The order comes from the channel count; any other count, a
719
+ zero-length buffer or another format throws MargoError code `unsupported` before any node is made. `setBuffer`
720
+ takes a buffer of the same order; a different order needs a new `BinauralAudio`. `ambixBasis(order, [front, left,
721
+ up])` gives the 1 to 16 harmonics of a direction, for encoding test signals as above.
722
+ - **Transport.** It is an `Audio`: `play`, `stop`, seeks, fades, filters, `volume` and `using` work as for any sound;
723
+ `loop` defaults to `true`. `getOutput()` is the stereo output node, for analysers and wet sends.
724
+ - **Orientation.** The listener's head orientation turns the virtual loudspeakers with the native HRTF panners, so the
725
+ field stays put in the world as the head turns. `setRotation([x, y, z, w])` turns the field itself in world
726
+ coordinates (normalised and copied; four finite values, not all zero, or a `state` error). Identity puts the bed's
727
+ front, left and up at world -Z, -X and +Y. The loudspeakers move with the listener's position, so the bed stays
728
+ infinitely distant; position changes move nothing you can hear.
729
+ - **Cost.** 32 HRTF panners plus `32 x (order + 1)^2` gain nodes (128, 288 or 512) and one splitter per bed, built
730
+ once; moving the head or the field writes the 96 panner positions, smoothed at `listener.smoothing`, and schedules
731
+ nothing when unchanged. No convolution, worklet or per-sample JavaScript. Several beds multiply that; a busy scene
732
+ usually needs one.
733
+ - **Localisation depends on the browser.** The HRTF set, its interpolation and so front/back and elevation accuracy are
734
+ the browser's, and none is personalised. The decode is tested against an independent offline render of the same 32
735
+ loudspeakers in real Web Audio (`tests/binaural-browser.js`, plus `tests/binaural.test.js` on stand-in audio);
736
+ listening tests and other browsers are not measured.
737
+ - `dispose()` (or `using`, or the listener's `dispose()`) disconnects the whole graph and keeps the buffer; it can be
738
+ called again, and `setRotation` after it throws code `disposed`.
739
+
740
+ The PCM proofs use real browser Web Audio offline rendering, without output-device PCM or listening measurements. Live Doppler regressions use real AudioContext nodes/state changes with controlled 60 Hz frame times and a 10.667 ms quantized audio clock. Long-loop markers at 130 bpm cover one hour at 8 kHz and five minutes each at 44.1/48 kHz; loop endpoints keep fractional sample positions rather than accumulating sample-rounding drift. Other browsers/devices remain unmeasured.
741
+
742
+ ## Offline spectrograms
743
+
744
+ `@margoengine/audio/spectrogram` analyses a whole array of samples, not the live frames an `AnalyserNode` gives. `stft`
745
+ cuts it into windowed frames (Hann by default; also Hamming, Blackman, 4-term Blackman-Harris, Kaiser by `beta`, or
746
+ your own coefficients from `windows`) and returns `real` and `imag` arrays of `frames x (size / 2 + 1)` bins. `istft`
747
+ puts the frames back by weighted overlap-add (Allen and Rabiner 1977, with the window-squared normaliser), and
748
+ `spectrogram` turns a spectrum into an image of bytes (or colours) for a texture. `resynthesize` estimates a signal
749
+ from a magnitude spectrogram, which is how an edited or painted spectrogram becomes sound, by the fast Griffin-Lim
750
+ algorithm (Griffin and Lim 1984; Perraudin, Balazs and Sondergaard 2013).
751
+
752
+ - Sizes are powers of two from 32 to 65536 (default 2048); `hop` runs from 1 to `size` (default `size / 4`). Frame k is
753
+ centred on sample `k * hop` by default (`center: true`, reflect padding; `pad: 'zero'` and `'edge'` also work).
754
+ - `istft` and `resynthesize` throw a coded `state` error when the window and hop do not overlap-add evenly: the smallest
755
+ over the largest summed squared window (`overlapRatio`) must be at least 0.1. Hann at hop `size / 4` gives 1, at
756
+ `size / 2` gives 0.5 and at 3/4 of `size` gives 0.04.
757
+ - `resynthesize(target, { iterations: 32, momentum: 0.99, init: 'random' })` returns `samples`, the spectral
758
+ `convergence` after each iteration and the number of frame FFTs it ran. Momentum 0 is the original algorithm.
759
+ - `stft(samples, { gpu })` (a compute context from `@margoengine/compute`, which loads then) transforms frames in
760
+ batches on the GPU and returns a promise; it agrees with the CPU path to 2e-7 of the peak. Pass an `AbortSignal` as
761
+ `signal` to stop between frames.
762
+
763
+ ```ts
764
+ import { istft, resynthesize, spectrogram, stft } from '@margoengine/audio/spectrogram';
765
+
766
+ // One second of a rising chirp, as a loaded file's channel data would be.
767
+ const rate = 48000;
768
+ const samples = Float32Array.from({ length: rate }, (_, i) => {
769
+ const t = i / rate;
770
+ return 0.8 * Math.sin(2 * Math.PI * (300 * t + 1500 * t * t));
771
+ });
772
+ const spec = stft(samples, { sampleRate: rate, size: 2048 });
773
+ const image = spectrogram(spec, { colormap: 'heat', range: [-80, 0], origin: 'high' });
774
+ // image.data is RGBA bytes, image.width x image.height: write it to an rgba8unorm texture with
775
+ // device.queue.writeTexture({ texture }, image.data, { bytesPerRow: image.width * 4 }, [image.width, image.height]).
776
+ const same = istft(spec); // the samples again, within 1e-6
777
+ // Keep only the magnitudes, as a painted spectrogram would, and get a signal back.
778
+ const magnitude = Float32Array.from(spec.real, (re, i) => Math.hypot(re, spec.imag[i]));
779
+ const { samples: estimate, convergence } = resynthesize(
780
+ { magnitude, frames: spec.frames, size: 2048, hop: spec.hop, length: samples.length },
781
+ { iterations: 16 },
782
+ );
783
+ console.log(image.width, image.height, same.length, estimate.length, convergence[convergence.length - 1] < convergence[0]);
784
+ ```
785
+
786
+ ## WAV files without Web Audio
787
+
788
+ `@margoengine/audio/wav` reads and writes RIFF WAVE files as plain bytes, so a stem or a mix can be made in Node, a
789
+ worker or a build script with no `AudioContext` and no `OfflineAudioContext`. `decodeWav` returns the sample rate and
790
+ one `Float32Array` per channel; `encodeWav` returns the file as a `Uint8Array` for `fs.writeFile` or a `Blob`.
791
+
792
+ - Reads 8-bit (unsigned), 16, 24 and 32-bit PCM and 32 and 64-bit float, plain or `WAVE_FORMAT_EXTENSIBLE`, with any
793
+ number of channels; `LIST`, `bext`, `iXML` and other chunks are skipped; a file still being written (data size
794
+ `0xFFFFFFFF` or past the end) reads to its end.
795
+ - Writes 16-bit PCM by default (`format: 'pcm8' | 'pcm16' | 'pcm24' | 'pcm32' | 'float32' | 'float64'`). More than two
796
+ channels, or 24 or 32-bit PCM or 64-bit float, get an extensible header with the usual channel mask (5.1 is `0x3F`).
797
+ Integer formats round to nearest, clamp (1.0 is the largest value, no wrap) and turn NaN into silence.
798
+ - A file written then read back has the same samples, and writing what was read gives the same bytes. ffmpeg and
799
+ Python's `wave` module read the files it writes.
800
+ - Not read: ADPCM, A-law, mu-law, compressed codecs inside WAV, and RF64 (over 4 GiB); they throw a coded error
801
+ ([errors#wav](https://margoengine.com/errors#wav)).
802
+ - Sources: Microsoft and IBM, Multimedia Programming Interface and Data Specifications 1.0 (1991), for the RIFF and PCM
803
+ layout; Microsoft, Multiple Channel Audio Data and WAVE Files (2001), for `WAVE_FORMAT_EXTENSIBLE`; EBU Tech 3285
804
+ (Broadcast Wave Format) for the extra chunks; EBU Tech 3306 (RF64) for why files over 4 GiB are refused.
805
+
806
+ ```ts
807
+ import { decodeWav, encodeWav } from '@margoengine/audio/wav';
808
+
809
+ // A second of a 440 Hz tone in the left channel and 660 Hz in the right, written as a 24-bit stereo file.
810
+ const rate = 48000;
811
+ const tone = (hz: number) => Float32Array.from({ length: rate }, (_, i) => 0.5 * Math.sin((2 * Math.PI * hz * i) / rate));
812
+ const file = encodeWav({ sampleRate: rate, channels: [tone(440), tone(660)] }, { format: 'pcm24' });
813
+ // In Node: await writeFile('mix.wav', file)
814
+ const audio = decodeWav(file);
815
+ console.log(file.byteLength, audio.sampleRate, audio.channels.length, audio.channels[0].length, audio.format);
816
+ ```
817
+
818
+ ## Clipping and silence checks
819
+
820
+ `@margoengine/audio/scan` checks decoded audio, in Node, a worker or a page, before it ships: a narration, a stem or a
821
+ mix read with `decodeWav`.
822
+
823
+ - `scanClipping(channels, sampleRate, { level?, run? })` finds every run of `run` (default 3) or more samples in a row
824
+ on one channel whose magnitude is at or over `level` of full scale (default 0.999). One full-scale sample is a peak,
825
+ not a clip; the level sits just under 1 so clipped audio that went through a lossy codec still counts. Returns
826
+ `{ runs, clippedSamples, peak }`, each run `{ channel, startSample, length, start, end }` with times in seconds.
827
+ - `findSilences(samples, sampleRate, { floorDb?, minSeconds?, window?, spans? })` finds runs of windows (default 10 ms)
828
+ whose level is under `floorDb` (default -50 dBFS) lasting at least `minSeconds` (default 2), only inside `spans`
829
+ (`[start, end]` seconds) when given; a silence never crosses a span's edge. The level is the mean square of all
830
+ channels in dBFS as AES17 defines it (a full-scale sine is 0 dBFS). Returns `{ start, end, duration, level }` per
831
+ silence, `level` being its loudest window. Edges are found to within one window.
832
+ - `samples` and `channels` take one channel or an array of them (Float32Array or number arrays, all one length).
833
+ - Loudness and true peak are `@margoengine/mixer/loudness`'s job (ITU-R BS.1770, EBU R 128).
834
+ - Web rivals: Tone.js and Howler meter live playback only and wavesurfer.js draws peaks; none scans decoded audio for
835
+ clips or silences. ffmpeg's `silencedetect` and `astats` filters are the command-line equivalent.
836
+ - Sources: AES17-2020 (full scale and dBFS); IEC 61606-3 and EBU Tech 3341 (sample and true peak); Aleinik, Matveev
837
+ and Raev, "Detection of clipped fragments in speech signals" (2014), and Eaton and Naylor, "Detection of clipping in
838
+ coded speech signals" (EUSIPCO 2013), for runs at the rail rather than single peaks; ITU-R BS.1770-5 (levels over
839
+ short blocks of all channels); ITU-T P.56 (2011) for speech activity with a hangover, which `minSeconds` plays.
840
+
841
+ ```ts
842
+ import { decodeWav, encodeWav } from '@margoengine/audio/wav';
843
+ import { findSilences, scanClipping } from '@margoengine/audio/scan';
844
+
845
+ // Two seconds of speech-like tone, four seconds of near silence, then a tone driven past full scale.
846
+ const rate = 48000;
847
+ const tone = (seconds: number, gain: number) =>
848
+ Float32Array.from({ length: seconds * rate }, (_, i) => Math.max(-1, Math.min(1, gain * Math.sin((2 * Math.PI * 220 * i) / rate))));
849
+ const voice = new Float32Array(8 * rate);
850
+ voice.set(tone(2, 0.3), 0);
851
+ voice.set(tone(2, 2), 6 * rate);
852
+ // In Node: decodeWav(await readFile('narration.wav'))
853
+ const { channels, sampleRate } = decodeWav(encodeWav({ sampleRate: rate, channels: [voice] }));
854
+ const clips = scanClipping(channels, sampleRate);
855
+ const silences = findSilences(channels, sampleRate, { floorDb: -50, minSeconds: 3, spans: [[0, 8]] });
856
+ console.log(clips.runs.length, clips.runs[0].start.toFixed(3), silences.map((s) => [s.start, s.end]));
857
+ ```
858
+
859
+ ## Sample rates and channel layouts without Web Audio
860
+
861
+ `@margoengine/audio/resample` converts decoded audio to another sample rate and channel count on plain `Float32Array`
862
+ channels, in Node, a worker or a page, with no `AudioContext`, `OfflineAudioContext` or ffmpeg: a take recorded at 44.1
863
+ kHz joins a 48 kHz narration read with `decodeWav`.
864
+
865
+ - `resample(audio, sampleRate, { channels?, zeroCrossings?, rolloff?, attenuation? })` takes `{ sampleRate, channels }`
866
+ (what `decodeWav` returns) and gives the same shape at the new rate. Each output sample is a sum of input samples
867
+ weighted by a Kaiser-windowed sinc centred on its time (bandlimited interpolation); when the rate goes down the sinc
868
+ widens so it also removes what the new rate cannot hold, and nothing folds back. The output holds
869
+ `ceil(length * sampleRate / input rate)` samples, so one second stays one second; samples past either end count as
870
+ silence. The same rate copies the samples.
871
+ - Defaults: `zeroCrossings` 32 (4 to 256) on each side, `rolloff` 0.92 (0.5 to 1) of the lower Nyquist frequency,
872
+ `attenuation` 90 dB (40 to 160) for the Kaiser window. At these a 1 kHz tone taken from 44.1 to 48 kHz is within
873
+ -80 dB of the exact sine, the response is flat within 0.1 dB to 0.86 of the lower Nyquist frequency (19.0 kHz for
874
+ 44.1 kHz to 48 kHz), and a tone at or above the lower Nyquist frequency comes out at least 90 dB down (tests in
875
+ `tests/resample.test.js`).
876
+ - `channels` mixes by `mixChannels(channels, count)`, also exported: the Web Audio speaker rules for mono, stereo, quad
877
+ and 5.1 up and down (5.1 to stereo puts the centre and surrounds in at -3 dB and drops the LFE), and a discrete copy
878
+ for any other pair (channels in order, missing ones silent, extra ones dropped).
879
+ - Rates are whole numbers from 1 to 768000; a bad rate or option throws a coded error
880
+ ([errors#audio-resample](https://margoengine.com/errors#audio-resample)).
881
+ - Web rivals: Tone.js, Howler and the Web Audio API itself resample only through an `AudioContext` or
882
+ `OfflineAudioContext`, so not in Node; ffmpeg's `aresample` (swr) is the command-line equivalent.
883
+ - Sources: J. O. Smith III and P. Gossett, "A flexible sampling-rate conversion method", ICASSP 1984, and J. O. Smith
884
+ III, Digital Audio Resampling Home Page (CCRMA, Stanford), for bandlimited interpolation from a filter table read
885
+ with linear interpolation; R. E. Crochiere and L. R. Rabiner, Multirate Digital Signal Processing (Prentice Hall,
886
+ 1983), for the lowpass at the lower Nyquist rate; J. F. Kaiser, "Nonrecursive digital filter design using the
887
+ I0-sinh window function", ISCAS 1974, and Oppenheim and Schafer, Discrete-Time Signal Processing, 3rd ed. (2010),
888
+ section 7.6, for the window and its beta; Laakso, Valimaki, Karjalainen and Laine, "Splitting the unit delay", IEEE
889
+ Signal Processing Magazine 13(1), 1996, doi:10.1109/79.482137, for why Lagrange and allpass interpolators were not
890
+ used; W3C Web Audio API (2021), "Channel Up-Mixing and Down-Mixing", for the speaker rules.
891
+
892
+ ```ts
893
+ import { decodeWav, encodeWav } from '@margoengine/audio/wav';
894
+ import { resample } from '@margoengine/audio/resample';
895
+
896
+ // A second of a 1 kHz mono take at 44.1 kHz, laid into a 48 kHz stereo voice.
897
+ const tone = Float32Array.from({ length: 44100 }, (_, i) => 0.5 * Math.sin((2 * Math.PI * 1000 * i) / 44100));
898
+ // In Node: decodeWav(await readFile('take.wav'))
899
+ const take = decodeWav(encodeWav({ sampleRate: 44100, channels: [tone] }, { format: 'float32' }));
900
+ const voice = resample(take, 48000, { channels: 2 });
901
+ console.log(voice.sampleRate, voice.channels.length, voice.channels[0].length); // 48000 2 48000
902
+ ```
903
+
904
+ ## Time-stretch at the same pitch
905
+
906
+ `@margoengine/audio/stretch` makes decoded audio longer or shorter without changing its pitch, on plain `Float32Array`
907
+ channels in Node, a worker or a page: a narration section or a recorded take made a few percent faster or slower to
908
+ fit its slot. The mixer's pitch shift is a real-time effect that changes pitch, not length; this changes length.
909
+
910
+ - `timeStretch(audio, factor, { frameMs?, toleranceMs? })` takes `{ sampleRate, channels }` (what `decodeWav`
911
+ returns) and returns the same shape, `round(length * factor)` samples long: `1.05` is 5 % longer (slower), `0.95` is
912
+ 5 % shorter (faster), from `0.25` to `4`. A factor of 1 copies the samples.
913
+ - It is WSOLA (waveform similarity overlap-add): Hann-windowed frames of `frameMs` (default 40, 10 to 200) are laid
914
+ half a frame apart in the output, each taken from near its place in the input, moved by up to `toleranceMs` (default
915
+ 10, 1 to 50) to where its waveform best continues the frame before it, so periods line up and the pitch stays. Every
916
+ channel uses the same frame positions, chosen on their mean, so the stereo image stays put.
917
+ - Tested on tones and chords: the pitch stays within 0.2 % and the level within 2 % at factors 0.8 to 1.25, and the
918
+ period of a two-note chord is unchanged (`tests/stretch.test.js`). WSOLA suits speech; for music with strong
919
+ transients and many voices use the phase vocoder below (Driedger and Mueller 2016).
920
+ - A bad factor or option throws a coded error ([errors#audio-stretch](https://margoengine.com/errors#audio-stretch)).
921
+ - Web rivals: Tone.js `GrainPlayer` and the `playbackRate` of Howler and `<audio>` (with `preservesPitch`) stretch
922
+ while playing, in a page; none returns stretched samples offline in Node. ffmpeg's `atempo` and `rubberband` filters
923
+ are the command-line equivalent.
924
+ - Sources: W. Verhelst and M. Roelands, "An overlap-add technique based on waveform similarity (WSOLA) for high quality
925
+ time-scale modification of speech", ICASSP 1993, doi:10.1109/ICASSP.1993.319366; S. Roucos and A. M. Wilgus, "High
926
+ quality time-scale modification for speech", ICASSP 1985, doi:10.1109/ICASSP.1985.1168381; J. Driedger and M.
927
+ Mueller, "A Review of Time-Scale Modification of Music Signals", Applied Sciences 6(2):57, 2016,
928
+ doi:10.3390/app6020057; compared and not used for this entry: J. L. Flanagan and R. M. Golden, "Phase vocoder", BSTJ 45(9), 1966,
929
+ doi:10.1002/j.1538-7305.1966.tb01706.x, and J. Laroche and M. Dolson, "Improved phase vocoder time-scale
930
+ modification of audio", IEEE TSAP 7(3), 1999, doi:10.1109/89.759041.
931
+
932
+ ```ts
933
+ import { timeStretch } from '@margoengine/audio/stretch';
934
+
935
+ // Two seconds of a 220 Hz tone made 5 % shorter to fit its slot, at the same pitch.
936
+ const rate = 48000;
937
+ const take = { sampleRate: rate, channels: [Float32Array.from({ length: 2 * rate }, (_, i) => 0.5 * Math.sin((2 * Math.PI * 220 * i) / rate))] };
938
+ const fitted = timeStretch(take, 0.95);
939
+ console.log(fitted.channels[0].length / rate); // 1.9
940
+ ```
941
+
942
+ ## Phase vocoder: time-stretch and pitch shift for music
943
+
944
+ `@margoengine/audio/vocoder` changes the length of decoded audio, its pitch, or both, for music and dense mixes where
945
+ WSOLA (above) doubles or smears notes. It takes and returns the same `{ sampleRate, channels }` shape, in Node, a
946
+ worker or a page, and returns promises: the work yields to the event loop as it goes, and an `AbortSignal` stops it.
947
+
948
+ - `timeStretch(audio, factor, options)` returns `round(length * factor)` samples, `factor` from `0.25` to `4`.
949
+ `options.semitones` (-24 to 24, default 0) moves the pitch in the same pass.
950
+ - `pitchShift(audio, semitones, options)` moves the pitch and keeps the length.
951
+ - `transients` (default `true`): when lengthening (`factor * 2 ** (semitones / 12)` above 1), attacks such as drum
952
+ hits are split from the sustained sound and stretched with a 6 ms window, so they stay sharp.
953
+ - `preserveFormants` (default `false`): keeps the spectral envelope in place while the pitch moves, so a shifted voice
954
+ keeps its character. `envelopeMs` (default 2, 0.2 to 10) sets how much detail the envelope follows.
955
+ - `frameMs` (default 85, 20 to 200; rounded to a power of two in samples): raise it for closely spaced low notes,
956
+ lower it for fast changes.
957
+ - `signal`: the promise rejects with the signal's reason.
958
+ - Every channel is turned by the same phase in each frequency bin, so level and phase differences between channels are
959
+ kept. The same input and options give the same output, and the input is not changed.
960
+ - A bad input or option rejects with a coded error ([errors#audio-vocoder](https://margoengine.com/errors#audio-vocoder)).
961
+
962
+ How it works: synthesis phase is integrated from both derivatives of the short-time phase, loudest bins first (Prusa
963
+ and Holighaus 2017), with the derivatives taken by reassignment operators (Auger and Flandrin 1995) in place of finite
964
+ differences; attacks are separated by median filtering (Fitzgerald 2010; Driedger, Mueller and Ewert 2014; Driedger,
965
+ Mueller and Disch 2014); the formant envelope is the true envelope (Roebel and Rodet 2005); a pitch shift is a stretch
966
+ followed by the windowed-sinc resampler of `/resample`.
967
+
968
+ Tested on generated signals (`tests/vocoder.test.js`): a stretched or shifted tone is within 0.02 % of its pitch and
969
+ 2 % of its level, with everything else at least 40 dB down; chord partials 62 Hz or more apart keep their frequency
970
+ within 0.1 Hz and level within 5 % at factors 0.75 and 1.6; a click lands at its stretched time with over 95 % of its
971
+ energy within 4 ms; noise bursts doubled in length have no pre-echo above -60 dB (above -35 dB with
972
+ `transients: false`). No listening test or comparison with another library has been run. `docs/limits.md` lists what it
973
+ does not do.
974
+
975
+ Web rivals: Rubber Band and Signalsmith Stretch builds in Wasm, SoundTouchJS (a time-domain method) and Tone.js
976
+ `PitchShift` (a delay line). This entry has no live form: it works on whole signals, offline.
977
+
978
+ ```ts
979
+ import { pitchShift, timeStretch } from '@margoengine/audio/vocoder';
980
+
981
+ // A second of a two-note chord, made 25 % longer, then moved up a minor third.
982
+ const rate = 48000;
983
+ const note = (hz: number, i: number) => 0.25 * Math.sin((2 * Math.PI * hz * i) / rate);
984
+ const chord = { sampleRate: rate, channels: [Float32Array.from({ length: rate }, (_, i) => note(220, i) + note(330, i))] };
985
+ const slower = await timeStretch(chord, 1.25, { signal: AbortSignal.timeout(60000) });
986
+ const higher = await pitchShift(chord, 3, { preserveFormants: true });
987
+ console.log(slower.channels[0].length, higher.channels[0].length); // 60000 48000
988
+ ```