@margoengine/audio 0.0.0-stage → 0.1.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.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +748 -3
- package/dist/ambisonics.d.ts +54 -0
- package/dist/ambisonics.js +118 -0
- package/dist/analyser.d.ts +45 -0
- package/dist/audio.d.ts +282 -0
- package/dist/binaural.d.ts +35 -0
- package/dist/binaural.js +123 -0
- package/dist/doppler.d.ts +44 -0
- package/dist/doppler.js +82 -0
- package/dist/errors-D8rc8kzg.js +7 -0
- package/dist/events.d.ts +54 -0
- package/dist/events.js +78 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +303 -0
- package/dist/listener.d.ts +116 -0
- package/dist/loader.d.ts +22 -0
- package/dist/math-C82bLsED.js +44 -0
- package/dist/math.d.ts +19 -0
- package/dist/music.d.ts +76 -0
- package/dist/music.js +106 -0
- package/dist/occlusion.d.ts +50 -0
- package/dist/occlusion.js +75 -0
- package/dist/outdoor.d.ts +37 -0
- package/dist/outdoor.js +46 -0
- package/dist/pan.d.ts +21 -0
- package/dist/pan.js +28 -0
- package/dist/rate-control-BiZ5FnNk.js +4 -0
- package/dist/rate-control.d.ts +5 -0
- package/dist/resample.d.ts +53 -0
- package/dist/resample.js +270 -0
- package/dist/scan.d.ts +66 -0
- package/dist/scan.js +75 -0
- package/dist/spectrogram-fft.d.ts +26 -0
- package/dist/spectrogram-windows.d.ts +24 -0
- package/dist/spectrogram.d.ts +143 -0
- package/dist/spectrogram.js +440 -0
- package/dist/sprites.d.ts +59 -0
- package/dist/sprites.js +99 -0
- package/dist/stretch.d.ts +25 -0
- package/dist/stretch.js +55 -0
- package/dist/voice-manager.d.ts +100 -0
- package/dist/voice-manager.js +178 -0
- package/dist/voices-CdfPmzIo.js +425 -0
- package/dist/voices.d.ts +45 -0
- package/dist/wav.d.ts +47 -0
- package/dist/wav.js +156 -0
- package/dist/zones.d.ts +43 -0
- package/dist/zones.js +75 -0
- package/package.json +127 -6
package/README.md
CHANGED
|
@@ -1,3 +1,748 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @margoengine/audio
|
|
2
|
+
|
|
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.
|
|
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
|
+
## Doppler
|
|
238
|
+
|
|
239
|
+
`@margoengine/audio/doppler` shifts buffer pitch from source and listener world motion.
|
|
240
|
+
Attach it after setting the buffer; the listener samples both poses after the sound update.
|
|
241
|
+
It works identically with WebGPU, native WebGL2 and WebGL2 compatibility rendering.
|
|
242
|
+
The audio root does not import this entry.
|
|
243
|
+
|
|
244
|
+
```ts
|
|
245
|
+
import {AudioListener, PositionalAudio} from 'margoengine/audio';
|
|
246
|
+
import {AudioDoppler} from 'margoengine/audio/doppler';
|
|
247
|
+
|
|
248
|
+
const context = new OfflineAudioContext(2, 24000, 48000);
|
|
249
|
+
using listener = new AudioListener({context, smoothing: 0});
|
|
250
|
+
listener.follow(null);
|
|
251
|
+
using sound = new PositionalAudio(listener, {rolloffFactor: 0});
|
|
252
|
+
const buffer = context.createBuffer(1, 48000, 48000);
|
|
253
|
+
buffer.getChannelData(0).forEach((_, i, a) => { a[i] = 0.2 * Math.sin(2 * Math.PI * 1000 * i / 48000); });
|
|
254
|
+
sound.setBuffer(buffer).setPosition(20, 0, 0).play();
|
|
255
|
+
using doppler = new AudioDoppler(sound);
|
|
256
|
+
listener.update();
|
|
257
|
+
const paused = context.suspend(0.128);
|
|
258
|
+
const rendered = context.startRendering();
|
|
259
|
+
await paused;
|
|
260
|
+
sound.setPosition(20 - 34.3 * context.currentTime, 0, 0);
|
|
261
|
+
listener.update();
|
|
262
|
+
console.log(doppler.ratio); // 1.111...: source approaching at 34.3 m/s
|
|
263
|
+
sound.playbackRate = 1.1; // authored pitch, composed with Doppler (also works on pooled voices)
|
|
264
|
+
console.log(doppler.playbackRate, sound.isDisposed); // 1.1, false
|
|
265
|
+
await context.resume();
|
|
266
|
+
console.log((await rendered).length); // 24000 frames, shifted tone after the motion sample
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
Options: `speedOfSound=343` m/s (finite, positive), `playbackRate=sound.playbackRate`
|
|
270
|
+
(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,
|
|
271
|
+
volume, fades, filters and the panner stay independent. Use one controller per sound;
|
|
272
|
+
duplicate attachment raises `attached`. Buffer sources only; other source kinds raise
|
|
273
|
+
`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.
|
|
274
|
+
|
|
275
|
+
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;
|
|
276
|
+
attached listeners do this automatically. Updates use existing playback-rate smoothing
|
|
277
|
+
(`listener.smoothing=0.02` s by default). Playback speed and duration change with pitch.
|
|
278
|
+
Do not combine with `Audio.sync`, which also owns playback rate.
|
|
279
|
+
|
|
280
|
+
The classical stationary-medium ratio is `(c + listener radial velocity) / (c + source
|
|
281
|
+
radial velocity)` with the axis pointing listener to source. Each radial Mach number
|
|
282
|
+
is clamped to -0.95..0.95, bounding the ratio to 1/39..39. This keeps extreme motion
|
|
283
|
+
finite; supersonic propagation, sonic booms, wind, travel delay and retarded positions
|
|
284
|
+
are outside this instantaneous approximation. Stop updating to freeze the last pitch;
|
|
285
|
+
dispose or reset to restore it. Sound disposal detaches on the next listener update;
|
|
286
|
+
listener teardown disposes controllers. Supports `using` and idempotent `dispose()`.
|
|
287
|
+
Node tests use stand-in audio. Real browser renders measure generated 1 kHz tones for
|
|
288
|
+
approach, recession, listener approach, co-motion and rest on all three rendering routes.
|
|
289
|
+
Generated audio/motion are stand-ins; recordings, listening quality, other browsers
|
|
290
|
+
and performance remain unmeasured.
|
|
291
|
+
|
|
292
|
+
## Sound event containers
|
|
293
|
+
|
|
294
|
+
`@margoengine/audio/events` selects decoded one-shots in random or sequence order,
|
|
295
|
+
with independent pitch and volume variation and an audio-clock cooldown. It reuses
|
|
296
|
+
`AudioVoicePool`; the audio root does not import it. WebGPU and both WebGL2 routes
|
|
297
|
+
use the same Web Audio graph.
|
|
298
|
+
|
|
299
|
+
```ts
|
|
300
|
+
import {AudioListener} from 'margoengine/audio';
|
|
301
|
+
import {AudioEventContainer} from 'margoengine/audio/events';
|
|
302
|
+
|
|
303
|
+
const context = new OfflineAudioContext(2, 14400, 48000);
|
|
304
|
+
using listener = new AudioListener({context});
|
|
305
|
+
const buffers = [600, 900].map(hz => {
|
|
306
|
+
const buffer = context.createBuffer(1, 3840, 48000);
|
|
307
|
+
buffer.getChannelData(0).forEach((_, i, a) => { a[i] = 0.2 * Math.sin(2 * Math.PI * hz * i / 48000); });
|
|
308
|
+
return buffer;
|
|
309
|
+
});
|
|
310
|
+
using footsteps = new AudioEventContainer(listener, buffers, {
|
|
311
|
+
mode: 'sequence', volume: [0.5, 0.8], pitch: [-50, 50], cooldown: 0.1,
|
|
312
|
+
});
|
|
313
|
+
footsteps.play([0, 0, -1]);
|
|
314
|
+
console.log(footsteps.play([0, 0, -1])); // null: cooldown does not consume a sequence step
|
|
315
|
+
const paused = context.suspend(0.128);
|
|
316
|
+
const rendered = context.startRendering();
|
|
317
|
+
await paused;
|
|
318
|
+
footsteps.play([0, 0, -1]); // second buffer
|
|
319
|
+
await context.resume();
|
|
320
|
+
console.log((await rendered).length); // 14400 frames
|
|
321
|
+
// In a live game, load buffers with listener.load(url, {signal}) and call play on game events.
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
`AudioEventContainer(listener, buffers, options)` needs a nonempty list of decoded,
|
|
325
|
+
positive-duration buffers. `mode='random'` chooses uniformly, excluding the previous
|
|
326
|
+
buffer index when there is more than one; `'sequence'` visits indices in order and
|
|
327
|
+
wraps. Repeated buffer objects at different indices remain separate choices.
|
|
328
|
+
`voices=4` preallocates that many voices per buffer; a full pool steals its oldest
|
|
329
|
+
voice. Total voices are buffer count times `voices`; there is no global container
|
|
330
|
+
voice limit. Returned voices can be moved or stopped while they play.
|
|
331
|
+
|
|
332
|
+
`volume=[1,1]` is a uniform linear gain range within 0..1. `pitch=[0,0]` is a uniform
|
|
333
|
+
cents range within -4800..4800, converted to playbackRate with `2 ** (cents / 1200)`;
|
|
334
|
+
pitch also changes duration. Endpoints are snapshotted, finite and ordered. `cooldown=0`
|
|
335
|
+
is a finite nonnegative interval in audio-clock seconds. A rejected play returns null
|
|
336
|
+
without consuming random draws or sequence state. Context suspension freezes cooldown;
|
|
337
|
+
a backwards clock accepts a new play and starts a new interval. Play positions default
|
|
338
|
+
to `[0,0,0]` in metres. Invalid positions or draws fail before stopping an existing voice.
|
|
339
|
+
|
|
340
|
+
`random=Math.random` can be replaced with a uniform function returning a finite number
|
|
341
|
+
in `[0,1)` for reproducible runs. Constant ranges and a single-buffer selection need
|
|
342
|
+
no draw. Draw order is selection (random mode with multiple buffers), volume, pitch.
|
|
343
|
+
`voiceOptions` defaults to the pool's spatial and clip defaults; looping, voice count,
|
|
344
|
+
volume, detune and playback rate are controlled by the container. No buffer is cloned
|
|
345
|
+
or loaded here; existing listener loading supports AbortSignal. No timers or waiting.
|
|
346
|
+
`lastIndex=-1` until the first accepted play; `stopAll()` retains history/cooldown.
|
|
347
|
+
`dispose()` and `using` release voices, preserve shared buffers and are idempotent;
|
|
348
|
+
listener teardown also disposes the container. Disposed use raises `disposed` with a
|
|
349
|
+
help link; invalid selections use `state` and invalid ranges use linked RangeError.
|
|
350
|
+
|
|
351
|
+
Node tests cover order, variation, exact cooldown boundaries, deterministic selection,
|
|
352
|
+
single-buffer play, overlap, stealing, teardown and failure atomicity. Real browser
|
|
353
|
+
PCM measures generated sequence/random tones and a silent cooldown gap beside WebGPU,
|
|
354
|
+
native WebGL2 and compatibility WebGL2. Generated audio/events are stand-ins; real
|
|
355
|
+
recordings, listening quality, other browsers and performance are unmeasured.
|
|
356
|
+
|
|
357
|
+
## Adaptive music
|
|
358
|
+
|
|
359
|
+
`@margoengine/audio/music` starts decoded stems together and changes their levels on
|
|
360
|
+
beat or bar boundaries. Install the optional peer `@margoengine/mixer` alongside audio;
|
|
361
|
+
the entry reuses mixer buses and audio-clock gain scheduling. WebGPU, native WebGL2
|
|
362
|
+
and compatibility WebGL2 share the same Web Audio graph.
|
|
363
|
+
|
|
364
|
+
```ts
|
|
365
|
+
import {AudioListener} from 'margoengine/audio';
|
|
366
|
+
import {AudioMusic} from 'margoengine/audio/music';
|
|
367
|
+
|
|
368
|
+
const context = new OfflineAudioContext(2, 72000, 48000);
|
|
369
|
+
using listener = new AudioListener({context});
|
|
370
|
+
const tone = (hz: number) => {
|
|
371
|
+
const buffer = context.createBuffer(1, 24000, 48000);
|
|
372
|
+
buffer.getChannelData(0).forEach((_, i, a) => { a[i] = 0.1 * Math.sin(2 * Math.PI * hz * i / 48000); });
|
|
373
|
+
return buffer;
|
|
374
|
+
};
|
|
375
|
+
using music = new AudioMusic(listener, {base: tone(600), drums: tone(900)}, {
|
|
376
|
+
explore: {base: -6}, combat: {base: -6, drums: -6},
|
|
377
|
+
}, {loopBeats: 1, leadTime: 0});
|
|
378
|
+
music.start('explore', 0);
|
|
379
|
+
console.log(music.transition('combat', {quantize: 'beat', after: 0.1})); // 0.5 seconds
|
|
380
|
+
console.log((await context.startRendering()).length); // 72000 frames
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
In a game, use `listener.load(url, {signal})` for authored stems and call
|
|
384
|
+
`transition('combat')` when game state changes. States map stem names to dB levels;
|
|
385
|
+
omitted stems and `-Infinity` are silent. States are copied at construction. Gains
|
|
386
|
+
must fit finite float32 linear values. This is gain layering of continuously running
|
|
387
|
+
loops: muted stems keep their phase. Every loop is its own source started at
|
|
388
|
+
`origin + k * loop` on the audio clock, so a browser that rounds start or loop points to
|
|
389
|
+
whole frames (Firefox) never drifts off the grid. An `OfflineAudioContext` render (a soundtrack bounce)
|
|
390
|
+
is scheduled a window of loops at a time and refilled at `suspend(time)` points, because every scheduled source costs
|
|
391
|
+
the renderer work on each render quantum until it ends: an hour at 130 bpm renders in under a second in Chromium
|
|
392
|
+
instead of 35 s. A browser without `suspend(time)` on offline contexts (Firefox), or an app that already holds a
|
|
393
|
+
suspend at the same render quantum, gets the whole render scheduled at once: the same samples, rendered more slowly.
|
|
394
|
+
No tempo analysis, stretching, sequencing of
|
|
395
|
+
different sections, streaming, or automatic loudness/headroom management.
|
|
396
|
+
|
|
397
|
+
Options: `bpm=120` positive finite quarter-note beats/minute, `beatsPerBar=4` and
|
|
398
|
+
`loopBeats=4` positive integers, `leadTime=0.05` finite nonnegative scheduling seconds,
|
|
399
|
+
`fade=0.02` finite nonnegative mixer exponential fade seconds (about 98% settled;
|
|
400
|
+
0 jumps). Each decoded buffer must cover `loopBeats * 60 / bpm` seconds. Only that
|
|
401
|
+
interval loops; trailing samples are unused. Author seamless, aligned stems; buffers
|
|
402
|
+
are shared. Tempo and loop length stay fixed for a transport.
|
|
403
|
+
|
|
404
|
+
`start(state, at=currentTime+leadTime)` requires a stopped transport and a finite
|
|
405
|
+
time at/after now; returns the common origin. `transition(state, {quantize='bar',
|
|
406
|
+
after=currentTime, fade=constructor default})` returns the first grid time at/after
|
|
407
|
+
both `after` and `currentTime+leadTime`, relative to that origin. Exact boundaries
|
|
408
|
+
are eligible. Schedule ahead of time for live playback; a main-thread call that
|
|
409
|
+
arrives late moves to the next eligible boundary. Audio-clock suspension freezes
|
|
410
|
+
the grid. No timers or frame scheduling. A new request replaces mixer automation
|
|
411
|
+
at/after its chosen boundary, preserving earlier transitions; fades are exponential,
|
|
412
|
+
not equal-power crossfades. Validate requests before changing playback.
|
|
413
|
+
|
|
414
|
+
`stop()` cuts sources immediately, including future starts. Restart resets phase and
|
|
415
|
+
pending automation. `dispose()`, `using`, and listener teardown release owned sources
|
|
416
|
+
and mixer buses, preserving buffers. Disposed use raises linked `disposed`; invalid
|
|
417
|
+
states/grid use linked `state` errors. No core/stage changes. Node stand-ins cover
|
|
418
|
+
scheduling and lifecycle; real browser generated-stem PCM checks phase, loop, layering
|
|
419
|
+
and beat/bar boundaries on all three routes. Recordings, listening quality, other
|
|
420
|
+
browsers and performance remain unmeasured.
|
|
421
|
+
|
|
422
|
+
## Reverb zones
|
|
423
|
+
|
|
424
|
+
`@margoengine/audio/zones` selects a room response as the listener moves through
|
|
425
|
+
axis-aligned areas. It reuses `@margoengine/mixer/reflections` and mixer automation;
|
|
426
|
+
install the optional `@margoengine/mixer` peer alongside audio. WebGPU and both
|
|
427
|
+
WebGL2 routes use the same Web Audio convolution graph.
|
|
428
|
+
|
|
429
|
+
```ts
|
|
430
|
+
import {AudioListener, Audio} from 'margoengine/audio';
|
|
431
|
+
import {AudioReverbZones} from 'margoengine/audio/zones';
|
|
432
|
+
|
|
433
|
+
const context = new OfflineAudioContext(2, 24000, 48000);
|
|
434
|
+
using listener = new AudioListener({context});
|
|
435
|
+
using zones = new AudioReverbZones(listener, [
|
|
436
|
+
{name: 'hall', min: [-4, -2, -4], max: [4, 2, 4],
|
|
437
|
+
reverb: {room: [8, 4, 8], seconds: 0.2}},
|
|
438
|
+
]);
|
|
439
|
+
const buffer = context.createBuffer(1, 4800, 48000);
|
|
440
|
+
buffer.getChannelData(0)[0] = 0.25;
|
|
441
|
+
using sound = new Audio(listener).setBuffer(buffer);
|
|
442
|
+
sound.getOutput().connect(zones.input); // additional wet send; the dry route already exists
|
|
443
|
+
sound.play();
|
|
444
|
+
console.log(zones.active); // hall
|
|
445
|
+
console.log((await context.startRendering()).length); // 24000 frames
|
|
446
|
+
sound.getOutput().disconnect(zones.input);
|
|
447
|
+
```
|
|
448
|
+
|
|
449
|
+
`AudioReverbZones(listener, zones, {fade=0.1})` copies finite ordered `min`/`max`
|
|
450
|
+
world bounds in metres. Names must be unique and nonempty. Bounds are inclusive;
|
|
451
|
+
o matching zone means a silent wet send. Greatest finite `priority=0` wins overlap;
|
|
452
|
+
equal priorities select the first listed zone. `gain=0.25` is linear wet-send gain
|
|
453
|
+
in 0..1, added to the unchanged dry route. Manage headroom for combined dry/wet audio.
|
|
454
|
+
`reverb={}` takes the existing [mixer room settings and defaults](../mixer/README.md#early-room-reflections),
|
|
455
|
+
with `mix` always 1 for wet-only output. Bounds select a response; they do not define
|
|
456
|
+
the response's room geometry or move its authored source/listener positions.
|
|
457
|
+
|
|
458
|
+
`fade=0.1` is finite nonnegative mixer exponential fade seconds (about 98% settled);
|
|
459
|
+
0 jumps. One convolution and response buffer per zone are prepared at construction.
|
|
460
|
+
Only selection/send gains change on movement. Old tails ring out after a switch or
|
|
461
|
+
exit; the input feed fades, preserving convolution state. Resource cost grows with
|
|
462
|
+
zone count and room response length; this is an authored zone model, without
|
|
463
|
+
continuous propagation, portals, diffraction or automatic room geometry analysis.
|
|
464
|
+
|
|
465
|
+
`active` reports the selected name or null. Attached listeners update selection each
|
|
466
|
+
frame after their pose; otherwise call `listener.update()` or `zones.update()` after
|
|
467
|
+
setting the listener pose. Selection follows game frames, fades follow the audio
|
|
468
|
+
clock. Unchanged selection schedules nothing. Empty zone lists are valid wet silence.
|
|
469
|
+
No loading, waits or timers. Listener loading already supports AbortSignal.
|
|
470
|
+
|
|
471
|
+
`dispose()`, `using` and listener teardown disconnect owned sends/effects immediately,
|
|
472
|
+
cutting tails. If a manually connected source will outlive the controller, disconnect
|
|
473
|
+
its connection into `zones.input`. Shared source dry routes stay independent. Disposed
|
|
474
|
+
updates raise linked `disposed`; invalid bounds/names/levels raise linked `state`.
|
|
475
|
+
Room settings use the mixer's validation. Node tests cover priority, boundaries,
|
|
476
|
+
immutable bounds, teardown and failure cleanup. Real browser PCM compares generated
|
|
477
|
+
impulses to existing mixer responses across room entry/switch/exit, including dry
|
|
478
|
+
sound and retained tails, on all three routes. Generated rooms/motion are stand-ins;
|
|
479
|
+
recordings, listening quality, other browsers and performance remain unmeasured.
|
|
480
|
+
|
|
481
|
+
## Ambisonic beds
|
|
482
|
+
|
|
483
|
+
`@margoengine/audio/ambisonics` plays and rotates first-order AmbiX beds (four
|
|
484
|
+
ACN/SN3D channels W,Y,Z,X). It uses Web Audio splitters, a rotation/decoder gain
|
|
485
|
+
matrix and a stereo merger on WebGPU, native WebGL2 and compatibility WebGL2.
|
|
486
|
+
|
|
487
|
+
```ts
|
|
488
|
+
import {AudioListener} from 'margoengine/audio';
|
|
489
|
+
import {AmbisonicAudio} from 'margoengine/audio/ambisonics';
|
|
490
|
+
|
|
491
|
+
const context = new OfflineAudioContext(2, 24000, 48000);
|
|
492
|
+
using listener = new AudioListener({context, smoothing: 0});
|
|
493
|
+
const buffer = context.createBuffer(4, 24000, 48000);
|
|
494
|
+
// A generated plane-wave tone from the recording's front: W = X, Y = Z = 0.
|
|
495
|
+
for (let i = 0; i < buffer.length; i++) {
|
|
496
|
+
const sample = 0.1 * Math.sin(2 * Math.PI * 600 * i / 48000);
|
|
497
|
+
buffer.getChannelData(0)[i] = sample;
|
|
498
|
+
buffer.getChannelData(3)[i] = sample;
|
|
499
|
+
}
|
|
500
|
+
using bed = new AmbisonicAudio(listener, buffer, {volume: 0.5});
|
|
501
|
+
bed.setRotation([0, Math.SQRT1_2, 0, Math.SQRT1_2]).play(); // 90-degree world Y rotation
|
|
502
|
+
console.log((await context.startRendering()).length); // 24000 frames
|
|
503
|
+
```
|
|
504
|
+
|
|
505
|
+
For a file, use `await listener.load(url, {signal})`, then construct the bed from
|
|
506
|
+
that decoded buffer. Four-channel PCM WAV is tested. Browser codec/container support
|
|
507
|
+
controls loading; this entry does not parse CAF adaptor matrices, Opus mapping
|
|
508
|
+
metadata or infer normalization from a buffer. Confirm ACN/SN3D before passing it.
|
|
509
|
+
`format='ambix'` is the only supported convention. FuMa, N3D, A-format, higher orders,
|
|
510
|
+
extra stereo channels and mixed-order layouts need conversion first; other formats
|
|
511
|
+
or channel counts raise `unsupported` with a help link. Buffers have positive finite
|
|
512
|
+
duration and are shared. No core/stage changes or additional peer dependencies.
|
|
513
|
+
|
|
514
|
+
The decoder uses two virtual cardioid microphones at +/-30 degrees about listener
|
|
515
|
+
forward: each output is `0.5 * (W + dot(direction, [X,Y,Z]))`, then output volume.
|
|
516
|
+
This gives orientation-dependent stereo ambience. It is not an HRTF/binaural decoder,
|
|
517
|
+
loudspeaker-layout decoder or a guarantee of headphone front/back/elevation localization.
|
|
518
|
+
ACN axes are X front, Y left, Z up. Identity field orientation maps those to engine
|
|
519
|
+
world -Z, -X, +Y respectively. `setRotation([x,y,z,w])` applies an active world-space
|
|
520
|
+
field rotation, normalized and copied. Listener orientation applies the inverse head
|
|
521
|
+
rotation to the bed. Translation is ignored for this infinitely distant ambience.
|
|
522
|
+
|
|
523
|
+
`loop=true` loops the complete buffer; `volume=1` is linear gain in 0..1; `smoothing`
|
|
524
|
+
defaults to `listener.smoothing` (0.02 s), a finite nonnegative time constant, with
|
|
525
|
+
0 immediate. Independent channel gains interpolate during orientation changes;
|
|
526
|
+
intermediate matrices during a fade are a blend, not an exact rigid rotation.
|
|
527
|
+
Use aligned/seamless loops and manage headroom. Eight gain paths and one source per
|
|
528
|
+
bed; no convolution, worklet, per-sample JavaScript or HRTF assets. Unchanged matrices
|
|
529
|
+
schedule nothing. `volume` can be changed independently of field rotation.
|
|
530
|
+
|
|
531
|
+
`play(at=context.currentTime)` starts from phase zero at/after now; a playing or
|
|
532
|
+
scheduled bed must be stopped before restart. `isPlaying` includes scheduled starts.
|
|
533
|
+
Natural end clears it for `loop=false`. `stop()` cuts and disconnects playback.
|
|
534
|
+
`dispose()`, `using` and listener teardown release decoder nodes and preserve buffers.
|
|
535
|
+
Disposed calls raise linked `disposed`; invalid values use linked `state` errors.
|
|
536
|
+
|
|
537
|
+
The listener updates the matrix each frame. For XR, feed the headset's world forward
|
|
538
|
+
and up vectors through `listener.follow(null).setPose(position, forward, up)` before
|
|
539
|
+
`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.
|
|
540
|
+
This entry adds no XR session/headset driver. Physical headset tracking and subjective
|
|
541
|
+
localization are unmeasured. CPU tests cover full quaternion yaw/pitch/roll basis
|
|
542
|
+
changes; browser PCM covers channel routing, looping, listener yaw and field yaw on
|
|
543
|
+
all three routes. Evidence uses generated independent tones and a licensed external
|
|
544
|
+
rain stimulus excerpt: [source/changes](tests/fixtures/NOTICE.md). That file validates
|
|
545
|
+
decoding/resampling and matrix output, not a microphone chain or recording provenance.
|
|
546
|
+
Listening quality, other browsers/devices and performance remain unmeasured.
|
|
547
|
+
|
|
548
|
+
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.
|
|
549
|
+
|
|
550
|
+
## Offline spectrograms
|
|
551
|
+
|
|
552
|
+
`@margoengine/audio/spectrogram` analyses a whole array of samples, not the live frames an `AnalyserNode` gives. `stft`
|
|
553
|
+
cuts it into windowed frames (Hann by default; also Hamming, Blackman, 4-term Blackman-Harris, Kaiser by `beta`, or
|
|
554
|
+
your own coefficients from `windows`) and returns `real` and `imag` arrays of `frames x (size / 2 + 1)` bins. `istft`
|
|
555
|
+
puts the frames back by weighted overlap-add (Allen and Rabiner 1977, with the window-squared normaliser), and
|
|
556
|
+
`spectrogram` turns a spectrum into an image of bytes (or colours) for a texture. `resynthesize` estimates a signal
|
|
557
|
+
from a magnitude spectrogram, which is how an edited or painted spectrogram becomes sound, by the fast Griffin-Lim
|
|
558
|
+
algorithm (Griffin and Lim 1984; Perraudin, Balazs and Sondergaard 2013).
|
|
559
|
+
|
|
560
|
+
- Sizes are powers of two from 32 to 65536 (default 2048); `hop` runs from 1 to `size` (default `size / 4`). Frame k is
|
|
561
|
+
centred on sample `k * hop` by default (`center: true`, reflect padding; `pad: 'zero'` and `'edge'` also work).
|
|
562
|
+
- `istft` and `resynthesize` throw a coded `state` error when the window and hop do not overlap-add evenly: the smallest
|
|
563
|
+
over the largest summed squared window (`overlapRatio`) must be at least 0.1. Hann at hop `size / 4` gives 1, at
|
|
564
|
+
`size / 2` gives 0.5 and at 3/4 of `size` gives 0.04.
|
|
565
|
+
- `resynthesize(target, { iterations: 32, momentum: 0.99, init: 'random' })` returns `samples`, the spectral
|
|
566
|
+
`convergence` after each iteration and the number of frame FFTs it ran. Momentum 0 is the original algorithm.
|
|
567
|
+
- `stft(samples, { gpu })` (a compute context from `@margoengine/compute`, which loads then) transforms frames in
|
|
568
|
+
batches on the GPU and returns a promise; it agrees with the CPU path to 2e-7 of the peak. Pass an `AbortSignal` as
|
|
569
|
+
`signal` to stop between frames.
|
|
570
|
+
|
|
571
|
+
```ts
|
|
572
|
+
import { istft, resynthesize, spectrogram, stft } from '@margoengine/audio/spectrogram';
|
|
573
|
+
|
|
574
|
+
// One second of a rising chirp, as a loaded file's channel data would be.
|
|
575
|
+
const rate = 48000;
|
|
576
|
+
const samples = Float32Array.from({ length: rate }, (_, i) => {
|
|
577
|
+
const t = i / rate;
|
|
578
|
+
return 0.8 * Math.sin(2 * Math.PI * (300 * t + 1500 * t * t));
|
|
579
|
+
});
|
|
580
|
+
const spec = stft(samples, { sampleRate: rate, size: 2048 });
|
|
581
|
+
const image = spectrogram(spec, { colormap: 'heat', range: [-80, 0], origin: 'high' });
|
|
582
|
+
// image.data is RGBA bytes, image.width x image.height: write it to an rgba8unorm texture with
|
|
583
|
+
// device.queue.writeTexture({ texture }, image.data, { bytesPerRow: image.width * 4 }, [image.width, image.height]).
|
|
584
|
+
const same = istft(spec); // the samples again, within 1e-6
|
|
585
|
+
// Keep only the magnitudes, as a painted spectrogram would, and get a signal back.
|
|
586
|
+
const magnitude = Float32Array.from(spec.real, (re, i) => Math.hypot(re, spec.imag[i]));
|
|
587
|
+
const { samples: estimate, convergence } = resynthesize(
|
|
588
|
+
{ magnitude, frames: spec.frames, size: 2048, hop: spec.hop, length: samples.length },
|
|
589
|
+
{ iterations: 16 },
|
|
590
|
+
);
|
|
591
|
+
console.log(image.width, image.height, same.length, estimate.length, convergence[convergence.length - 1] < convergence[0]);
|
|
592
|
+
```
|
|
593
|
+
|
|
594
|
+
## WAV files without Web Audio
|
|
595
|
+
|
|
596
|
+
`@margoengine/audio/wav` reads and writes RIFF WAVE files as plain bytes, so a stem or a mix can be made in Node, a
|
|
597
|
+
worker or a build script with no `AudioContext` and no `OfflineAudioContext`. `decodeWav` returns the sample rate and
|
|
598
|
+
one `Float32Array` per channel; `encodeWav` returns the file as a `Uint8Array` for `fs.writeFile` or a `Blob`.
|
|
599
|
+
|
|
600
|
+
- Reads 8-bit (unsigned), 16, 24 and 32-bit PCM and 32 and 64-bit float, plain or `WAVE_FORMAT_EXTENSIBLE`, with any
|
|
601
|
+
number of channels; `LIST`, `bext`, `iXML` and other chunks are skipped; a file still being written (data size
|
|
602
|
+
`0xFFFFFFFF` or past the end) reads to its end.
|
|
603
|
+
- Writes 16-bit PCM by default (`format: 'pcm8' | 'pcm16' | 'pcm24' | 'pcm32' | 'float32' | 'float64'`). More than two
|
|
604
|
+
channels, or 24 or 32-bit PCM or 64-bit float, get an extensible header with the usual channel mask (5.1 is `0x3F`).
|
|
605
|
+
Integer formats round to nearest, clamp (1.0 is the largest value, no wrap) and turn NaN into silence.
|
|
606
|
+
- A file written then read back has the same samples, and writing what was read gives the same bytes. ffmpeg and
|
|
607
|
+
Python's `wave` module read the files it writes.
|
|
608
|
+
- Not read: ADPCM, A-law, mu-law, compressed codecs inside WAV, and RF64 (over 4 GiB); they throw a coded error
|
|
609
|
+
([errors#wav](https://margoengine.com/errors#wav)).
|
|
610
|
+
- Sources: Microsoft and IBM, Multimedia Programming Interface and Data Specifications 1.0 (1991), for the RIFF and PCM
|
|
611
|
+
layout; Microsoft, Multiple Channel Audio Data and WAVE Files (2001), for `WAVE_FORMAT_EXTENSIBLE`; EBU Tech 3285
|
|
612
|
+
(Broadcast Wave Format) for the extra chunks; EBU Tech 3306 (RF64) for why files over 4 GiB are refused.
|
|
613
|
+
|
|
614
|
+
```ts
|
|
615
|
+
import { decodeWav, encodeWav } from '@margoengine/audio/wav';
|
|
616
|
+
|
|
617
|
+
// A second of a 440 Hz tone in the left channel and 660 Hz in the right, written as a 24-bit stereo file.
|
|
618
|
+
const rate = 48000;
|
|
619
|
+
const tone = (hz: number) => Float32Array.from({ length: rate }, (_, i) => 0.5 * Math.sin((2 * Math.PI * hz * i) / rate));
|
|
620
|
+
const file = encodeWav({ sampleRate: rate, channels: [tone(440), tone(660)] }, { format: 'pcm24' });
|
|
621
|
+
// In Node: await writeFile('mix.wav', file)
|
|
622
|
+
const audio = decodeWav(file);
|
|
623
|
+
console.log(file.byteLength, audio.sampleRate, audio.channels.length, audio.channels[0].length, audio.format);
|
|
624
|
+
```
|
|
625
|
+
|
|
626
|
+
## Clipping and silence checks
|
|
627
|
+
|
|
628
|
+
`@margoengine/audio/scan` checks decoded audio, in Node, a worker or a page, before it ships: a narration, a stem or a
|
|
629
|
+
mix read with `decodeWav`.
|
|
630
|
+
|
|
631
|
+
- `scanClipping(channels, sampleRate, { level?, run? })` finds every run of `run` (default 3) or more samples in a row
|
|
632
|
+
on one channel whose magnitude is at or over `level` of full scale (default 0.999). One full-scale sample is a peak,
|
|
633
|
+
not a clip; the level sits just under 1 so clipped audio that went through a lossy codec still counts. Returns
|
|
634
|
+
`{ runs, clippedSamples, peak }`, each run `{ channel, startSample, length, start, end }` with times in seconds.
|
|
635
|
+
- `findSilences(samples, sampleRate, { floorDb?, minSeconds?, window?, spans? })` finds runs of windows (default 10 ms)
|
|
636
|
+
whose level is under `floorDb` (default -50 dBFS) lasting at least `minSeconds` (default 2), only inside `spans`
|
|
637
|
+
(`[start, end]` seconds) when given; a silence never crosses a span's edge. The level is the mean square of all
|
|
638
|
+
channels in dBFS as AES17 defines it (a full-scale sine is 0 dBFS). Returns `{ start, end, duration, level }` per
|
|
639
|
+
silence, `level` being its loudest window. Edges are found to within one window.
|
|
640
|
+
- `samples` and `channels` take one channel or an array of them (Float32Array or number arrays, all one length).
|
|
641
|
+
- Loudness and true peak are `@margoengine/mixer/loudness`'s job (ITU-R BS.1770, EBU R 128).
|
|
642
|
+
- Web rivals: Tone.js and Howler meter live playback only and wavesurfer.js draws peaks; none scans decoded audio for
|
|
643
|
+
clips or silences. ffmpeg's `silencedetect` and `astats` filters are the command-line equivalent.
|
|
644
|
+
- Sources: AES17-2020 (full scale and dBFS); IEC 61606-3 and EBU Tech 3341 (sample and true peak); Aleinik, Matveev
|
|
645
|
+
and Raev, "Detection of clipped fragments in speech signals" (2014), and Eaton and Naylor, "Detection of clipping in
|
|
646
|
+
coded speech signals" (EUSIPCO 2013), for runs at the rail rather than single peaks; ITU-R BS.1770-5 (levels over
|
|
647
|
+
short blocks of all channels); ITU-T P.56 (2011) for speech activity with a hangover, which `minSeconds` plays.
|
|
648
|
+
|
|
649
|
+
```ts
|
|
650
|
+
import { decodeWav, encodeWav } from '@margoengine/audio/wav';
|
|
651
|
+
import { findSilences, scanClipping } from '@margoengine/audio/scan';
|
|
652
|
+
|
|
653
|
+
// Two seconds of speech-like tone, four seconds of near silence, then a tone driven past full scale.
|
|
654
|
+
const rate = 48000;
|
|
655
|
+
const tone = (seconds: number, gain: number) =>
|
|
656
|
+
Float32Array.from({ length: seconds * rate }, (_, i) => Math.max(-1, Math.min(1, gain * Math.sin((2 * Math.PI * 220 * i) / rate))));
|
|
657
|
+
const voice = new Float32Array(8 * rate);
|
|
658
|
+
voice.set(tone(2, 0.3), 0);
|
|
659
|
+
voice.set(tone(2, 2), 6 * rate);
|
|
660
|
+
// In Node: decodeWav(await readFile('narration.wav'))
|
|
661
|
+
const { channels, sampleRate } = decodeWav(encodeWav({ sampleRate: rate, channels: [voice] }));
|
|
662
|
+
const clips = scanClipping(channels, sampleRate);
|
|
663
|
+
const silences = findSilences(channels, sampleRate, { floorDb: -50, minSeconds: 3, spans: [[0, 8]] });
|
|
664
|
+
console.log(clips.runs.length, clips.runs[0].start.toFixed(3), silences.map((s) => [s.start, s.end]));
|
|
665
|
+
```
|
|
666
|
+
|
|
667
|
+
## Sample rates and channel layouts without Web Audio
|
|
668
|
+
|
|
669
|
+
`@margoengine/audio/resample` converts decoded audio to another sample rate and channel count on plain `Float32Array`
|
|
670
|
+
channels, in Node, a worker or a page, with no `AudioContext`, `OfflineAudioContext` or ffmpeg: a take recorded at 44.1
|
|
671
|
+
kHz joins a 48 kHz narration read with `decodeWav`.
|
|
672
|
+
|
|
673
|
+
- `resample(audio, sampleRate, { channels?, zeroCrossings?, rolloff?, attenuation? })` takes `{ sampleRate, channels }`
|
|
674
|
+
(what `decodeWav` returns) and gives the same shape at the new rate. Each output sample is a sum of input samples
|
|
675
|
+
weighted by a Kaiser-windowed sinc centred on its time (bandlimited interpolation); when the rate goes down the sinc
|
|
676
|
+
widens so it also removes what the new rate cannot hold, and nothing folds back. The output holds
|
|
677
|
+
`ceil(length * sampleRate / input rate)` samples, so one second stays one second; samples past either end count as
|
|
678
|
+
silence. The same rate copies the samples.
|
|
679
|
+
- Defaults: `zeroCrossings` 32 (4 to 256) on each side, `rolloff` 0.92 (0.5 to 1) of the lower Nyquist frequency,
|
|
680
|
+
`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
|
|
681
|
+
-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
|
|
682
|
+
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
|
|
683
|
+
`tests/resample.test.js`).
|
|
684
|
+
- `channels` mixes by `mixChannels(channels, count)`, also exported: the Web Audio speaker rules for mono, stereo, quad
|
|
685
|
+
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
|
|
686
|
+
for any other pair (channels in order, missing ones silent, extra ones dropped).
|
|
687
|
+
- Rates are whole numbers from 1 to 768000; a bad rate or option throws a coded error
|
|
688
|
+
([errors#audio-resample](https://margoengine.com/errors#audio-resample)).
|
|
689
|
+
- Web rivals: Tone.js, Howler and the Web Audio API itself resample only through an `AudioContext` or
|
|
690
|
+
`OfflineAudioContext`, so not in Node; ffmpeg's `aresample` (swr) is the command-line equivalent.
|
|
691
|
+
- Sources: J. O. Smith III and P. Gossett, "A flexible sampling-rate conversion method", ICASSP 1984, and J. O. Smith
|
|
692
|
+
III, Digital Audio Resampling Home Page (CCRMA, Stanford), for bandlimited interpolation from a filter table read
|
|
693
|
+
with linear interpolation; R. E. Crochiere and L. R. Rabiner, Multirate Digital Signal Processing (Prentice Hall,
|
|
694
|
+
1983), for the lowpass at the lower Nyquist rate; J. F. Kaiser, "Nonrecursive digital filter design using the
|
|
695
|
+
I0-sinh window function", ISCAS 1974, and Oppenheim and Schafer, Discrete-Time Signal Processing, 3rd ed. (2010),
|
|
696
|
+
section 7.6, for the window and its beta; Laakso, Valimaki, Karjalainen and Laine, "Splitting the unit delay", IEEE
|
|
697
|
+
Signal Processing Magazine 13(1), 1996, doi:10.1109/79.482137, for why Lagrange and allpass interpolators were not
|
|
698
|
+
used; W3C Web Audio API (2021), "Channel Up-Mixing and Down-Mixing", for the speaker rules.
|
|
699
|
+
|
|
700
|
+
```ts
|
|
701
|
+
import { decodeWav, encodeWav } from '@margoengine/audio/wav';
|
|
702
|
+
import { resample } from '@margoengine/audio/resample';
|
|
703
|
+
|
|
704
|
+
// A second of a 1 kHz mono take at 44.1 kHz, laid into a 48 kHz stereo voice.
|
|
705
|
+
const tone = Float32Array.from({ length: 44100 }, (_, i) => 0.5 * Math.sin((2 * Math.PI * 1000 * i) / 44100));
|
|
706
|
+
// In Node: decodeWav(await readFile('take.wav'))
|
|
707
|
+
const take = decodeWav(encodeWav({ sampleRate: 44100, channels: [tone] }, { format: 'float32' }));
|
|
708
|
+
const voice = resample(take, 48000, { channels: 2 });
|
|
709
|
+
console.log(voice.sampleRate, voice.channels.length, voice.channels[0].length); // 48000 2 48000
|
|
710
|
+
```
|
|
711
|
+
|
|
712
|
+
## Time-stretch at the same pitch
|
|
713
|
+
|
|
714
|
+
`@margoengine/audio/stretch` makes decoded audio longer or shorter without changing its pitch, on plain `Float32Array`
|
|
715
|
+
channels in Node, a worker or a page: a narration section or a recorded take made a few percent faster or slower to
|
|
716
|
+
fit its slot. The mixer's pitch shift is a real-time effect that changes pitch, not length; this changes length.
|
|
717
|
+
|
|
718
|
+
- `timeStretch(audio, factor, { frameMs?, toleranceMs? })` takes `{ sampleRate, channels }` (what `decodeWav`
|
|
719
|
+
returns) and returns the same shape, `round(length * factor)` samples long: `1.05` is 5 % longer (slower), `0.95` is
|
|
720
|
+
5 % shorter (faster), from `0.25` to `4`. A factor of 1 copies the samples.
|
|
721
|
+
- It is WSOLA (waveform similarity overlap-add): Hann-windowed frames of `frameMs` (default 40, 10 to 200) are laid
|
|
722
|
+
half a frame apart in the output, each taken from near its place in the input, moved by up to `toleranceMs` (default
|
|
723
|
+
10, 1 to 50) to where its waveform best continues the frame before it, so periods line up and the pitch stays. Every
|
|
724
|
+
channel uses the same frame positions, chosen on their mean, so the stereo image stays put.
|
|
725
|
+
- 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
|
|
726
|
+
period of a two-note chord is unchanged (`tests/stretch.test.js`). WSOLA suits speech; for music with strong
|
|
727
|
+
transients and many voices a phase vocoder can sound better (Driedger and Mueller 2016), and it is not offered here.
|
|
728
|
+
- A bad factor or option throws a coded error ([errors#audio-stretch](https://margoengine.com/errors#audio-stretch)).
|
|
729
|
+
- Web rivals: Tone.js `GrainPlayer` and the `playbackRate` of Howler and `<audio>` (with `preservesPitch`) stretch
|
|
730
|
+
while playing, in a page; none returns stretched samples offline in Node. ffmpeg's `atempo` and `rubberband` filters
|
|
731
|
+
are the command-line equivalent.
|
|
732
|
+
- Sources: W. Verhelst and M. Roelands, "An overlap-add technique based on waveform similarity (WSOLA) for high quality
|
|
733
|
+
time-scale modification of speech", ICASSP 1993, doi:10.1109/ICASSP.1993.319366; S. Roucos and A. M. Wilgus, "High
|
|
734
|
+
quality time-scale modification for speech", ICASSP 1985, doi:10.1109/ICASSP.1985.1168381; J. Driedger and M.
|
|
735
|
+
Mueller, "A Review of Time-Scale Modification of Music Signals", Applied Sciences 6(2):57, 2016,
|
|
736
|
+
doi:10.3390/app6020057; compared and not used: J. L. Flanagan and R. M. Golden, "Phase vocoder", BSTJ 45(9), 1966,
|
|
737
|
+
doi:10.1002/j.1538-7305.1966.tb01706.x, and J. Laroche and M. Dolson, "Improved phase vocoder time-scale
|
|
738
|
+
modification of audio", IEEE TSAP 7(3), 1999, doi:10.1109/89.759041.
|
|
739
|
+
|
|
740
|
+
```ts
|
|
741
|
+
import { timeStretch } from '@margoengine/audio/stretch';
|
|
742
|
+
|
|
743
|
+
// Two seconds of a 220 Hz tone made 5 % shorter to fit its slot, at the same pitch.
|
|
744
|
+
const rate = 48000;
|
|
745
|
+
const take = { sampleRate: rate, channels: [Float32Array.from({ length: 2 * rate }, (_, i) => 0.5 * Math.sin((2 * Math.PI * 220 * i) / rate))] };
|
|
746
|
+
const fitted = timeStretch(take, 0.95);
|
|
747
|
+
console.log(fitted.channels[0].length / rate); // 1.9
|
|
748
|
+
```
|