@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.
Files changed (51) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +748 -3
  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 +46 -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 +270 -0
  33. package/dist/scan.d.ts +66 -0
  34. package/dist/scan.js +75 -0
  35. package/dist/spectrogram-fft.d.ts +26 -0
  36. package/dist/spectrogram-windows.d.ts +24 -0
  37. package/dist/spectrogram.d.ts +143 -0
  38. package/dist/spectrogram.js +440 -0
  39. package/dist/sprites.d.ts +59 -0
  40. package/dist/sprites.js +99 -0
  41. package/dist/stretch.d.ts +25 -0
  42. package/dist/stretch.js +55 -0
  43. package/dist/voice-manager.d.ts +100 -0
  44. package/dist/voice-manager.js +178 -0
  45. package/dist/voices-CdfPmzIo.js +425 -0
  46. package/dist/voices.d.ts +45 -0
  47. package/dist/wav.d.ts +47 -0
  48. package/dist/wav.js +156 -0
  49. package/dist/zones.d.ts +43 -0
  50. package/dist/zones.js +75 -0
  51. package/package.json +127 -6
@@ -0,0 +1,425 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const a=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { n as e, r as t } from "./errors-D8rc8kzg.js";
5
+ import { i as n, r } from "./math-C82bLsED.js";
6
+ import { t as i } from "./rate-control-BiZ5FnNk.js";
7
+ import { engineRuntime as __margoRuntime, meshRuntime as o } from "@margoengine/core/extension";
8
+ //#region ../shared/visibility.js
9
+ function s(e, t) {
10
+ for (let n = t; n >= 0; n = e.parents?.[n] ?? -1) if (e.hidden[n]) return !0;
11
+ return !1;
12
+ }
13
+ //#endregion
14
+ //#region src/audio.ts
15
+ var c = [
16
+ 0,
17
+ 0,
18
+ 1
19
+ ], l = /* @__PURE__ */ new WeakMap(), u = (e, t) => {
20
+ if (e) try {
21
+ t ? e.disconnect(t) : e.disconnect();
22
+ } catch {}
23
+ }, d = (e, t, n = -Infinity) => {
24
+ if (typeof e != "number" || !Number.isFinite(e) || e < n) throw RangeError(`${t} must be a finite number${n > -Infinity ? ` >= ${n}` : ""}`);
25
+ return e;
26
+ }, f = class t {
27
+ static {
28
+ this.syncTolerance = .05;
29
+ }
30
+ constructor(e, t = {}) {
31
+ this.buffer = null, this.source = null, this.kind = null, this.media = null, this.playing = !1, this.endedNaturally = !1, this.startedAt = 0, this.progress = 0, this.filterList = [], this.muted = !1, this.disposed = !1, this.fading = !1, this.onMediaEnded = () => {
32
+ this.playing && !this.loopValue && (this.playing = !1, this.onEnded?.(this));
33
+ }, this.listener = e, this.context = e.context, this.loopValue = t.loop ?? !1, this.loopStartValue = d(t.loopStart ?? 0, "loopStart", 0), this.loopEndValue = d(t.loopEnd ?? 0, "loopEnd", 0), this.rateValue = d(t.playbackRate ?? 1, "playbackRate"), this.detuneValue = d(t.detune ?? 0, "detune"), this.offsetValue = d(t.offset ?? 0, "offset", 0), this.durationValue = t.duration === void 0 ? void 0 : d(t.duration, "duration", 0), this.timelineStartValue = d(t.timelineStart ?? 0, "timelineStart"), this.volumeValue = d(t.volume ?? 1, "volume", 0), this.autoplay = t.autoplay ?? !1, this.onEnded = t.onEnded ?? null, this.gain = this.context.createGain(), this.gain.gain.setValueAtTime(this.volumeValue, this.context.currentTime), this.fade = this.context.createGain(), this.fade.connect(this.gain), this.connectOutput(), t.filters?.length && this.setFilters(t.filters), e.addSource(this);
34
+ }
35
+ getOutput() {
36
+ return this.gain;
37
+ }
38
+ connectOutput() {
39
+ this.getOutput().connect(this.listener.input);
40
+ }
41
+ get isPlaying() {
42
+ return this.playing;
43
+ }
44
+ get isDisposed() {
45
+ return this.disposed;
46
+ }
47
+ get sourceType() {
48
+ return this.kind;
49
+ }
50
+ setBuffer(e) {
51
+ return this.replaceSource(), this.buffer = e, this.kind = "buffer", this.progress = 0, this.autoplay && this.play(), this;
52
+ }
53
+ setMediaElementSource(e) {
54
+ this.replaceSource();
55
+ let t = l.get(this.context);
56
+ t || (t = /* @__PURE__ */ new WeakMap(), l.set(this.context, t));
57
+ let n = t.get(e);
58
+ return n || (n = this.context.createMediaElementSource(e), t.set(e, n)), this.kind = "media", this.media = e, this.source = n, e.loop = this.loopValue, e.playbackRate = this.rateValue, e.addEventListener("ended", this.onMediaEnded), n.connect(this.head), this.playing = !e.paused, this;
59
+ }
60
+ setMediaStreamSource(e) {
61
+ return this.replaceSource(), this.kind = "stream", this.source = this.context.createMediaStreamSource(e), this;
62
+ }
63
+ setNodeSource(e) {
64
+ return this.replaceSource(), this.kind = "node", this.source = e, this;
65
+ }
66
+ play(t = 0) {
67
+ if (this.assertLive(), d(t, "delay", 0), this.playing) return this;
68
+ if (this.endedNaturally = !1, this.fading || this.setFade(1), this.kind === "buffer") this.startBuffer(this.context.currentTime + t);
69
+ else if (this.kind === "media") {
70
+ let e = this.media;
71
+ t > 0 ? (this.clearTimer(), this.fadeTimer = setTimeout(() => {
72
+ this.fadeTimer = void 0, this.playing && e.play().catch(() => {});
73
+ }, t * 1e3)) : e.play().catch(() => {});
74
+ } else if (this.kind === "stream" || this.kind === "node") this.source.connect(this.head);
75
+ else throw e("state", "Audio has no source; call setBuffer, setMediaElementSource, setMediaStreamSource or setNodeSource first");
76
+ return this.playing = !0, this;
77
+ }
78
+ pause() {
79
+ return this.playing && (this.playing = !1, this.clearTimer(), this.kind === "buffer" ? (this.progress += Math.max(this.context.currentTime - this.startedAt, 0) * this.speed, this.progress = this.playhead(this.buffer.duration) - this.offsetValue, this.stopNode()) : this.haltOther(!1)), this;
80
+ }
81
+ stop(e = 0) {
82
+ return d(e, "delay", 0), this.playing = !1, this.endedNaturally = !1, this.progress = 0, this.clearTimer(), this.kind === "buffer" ? this.stopNode(e) : e > 0 ? this.fadeTimer = setTimeout(() => {
83
+ this.fadeTimer = void 0, this.haltOther(!0);
84
+ }, e * 1e3) : this.haltOther(!0), this;
85
+ }
86
+ seek(e) {
87
+ return d(e, "seconds", 0), this.endedNaturally = !1, this.media ? this.media.currentTime = e : this.buffer && (this.progress = e - this.offsetValue, this.playing && this.startBuffer(Math.max(this.context.currentTime, this.startedAt))), this;
88
+ }
89
+ sync(e, n, r = 1) {
90
+ d(e, "timelineSeconds"), d(r, "rate");
91
+ let i = this.buffer;
92
+ if (!i) return this;
93
+ let a = e - this.timelineStartValue, o = Math.min(i.duration - this.offsetValue, this.durationValue ?? Infinity), s = this.loopValue ? Infinity : o - a;
94
+ if (!n || r <= 0 || a < 0 || s <= (this.endedNaturally ? t.syncTolerance : 0)) return this.pause(), (!n || r <= 0 || a < 0) && (this.endedNaturally = !1), this.progress = Math.max(0, this.loopValue ? a : Math.min(a, o)), this;
95
+ if (r !== this.rateValue && (this.playbackRate = r), !this.playing) return this.progress = a, this.play();
96
+ let c = this.playhead(i.duration, a), l = this.currentTime, u = Math.abs(c - l);
97
+ if (this.loopValue) {
98
+ let e = this.loopStartValue, t = this.loopEndValue > 0 ? Math.min(this.loopEndValue, i.duration) : i.duration;
99
+ t > e || (e = 0, t = i.duration), c >= e && l >= e && (u = Math.min(u, t - e - u));
100
+ }
101
+ return u > t.syncTolerance && this.seek(c), this;
102
+ }
103
+ fadeIn(e) {
104
+ d(e, "seconds", 0);
105
+ let t = this.fade.gain, n = this.context.currentTime;
106
+ t.cancelScheduledValues(n), t.setValueAtTime(0, n), t.linearRampToValueAtTime(1, n + e), this.fading = !0;
107
+ try {
108
+ this.playing || this.play();
109
+ } finally {
110
+ this.fading = !1;
111
+ }
112
+ return this;
113
+ }
114
+ fadeOut(e, { pause: t = !1 } = {}) {
115
+ if (d(e, "seconds", 0), !this.playing) return this;
116
+ let n = this.fade.gain, r = this.context.currentTime;
117
+ return n.cancelScheduledValues(r), n.setValueAtTime(n.value, r), n.linearRampToValueAtTime(0, r + e), !t && this.kind === "buffer" ? this.stop(e) : (this.clearTimer(), this.fadeTimer = setTimeout(() => {
118
+ this.fadeTimer = void 0, t ? this.pause() : this.stop();
119
+ }, e * 1e3)), this;
120
+ }
121
+ setFilters(e) {
122
+ let t = this.head;
123
+ this.source && this.isSourceConnected && u(this.source, t);
124
+ for (let e of this.filterList) u(e);
125
+ this.filterList = [...e];
126
+ for (let e = 0; e < this.filterList.length; e++) this.filterList[e].connect(this.filterList[e + 1] ?? this.fade);
127
+ return this.source && this.isSourceConnected && this.source.connect(this.head), this;
128
+ }
129
+ getFilters() {
130
+ return [...this.filterList];
131
+ }
132
+ setFilter(e) {
133
+ return this.setFilters(e ? [e] : []);
134
+ }
135
+ getFilter() {
136
+ return this.filterList[0] ?? null;
137
+ }
138
+ get volume() {
139
+ return this.volumeValue;
140
+ }
141
+ set volume(e) {
142
+ this.volumeValue = d(e, "volume", 0), this.writeGain();
143
+ }
144
+ get loop() {
145
+ return this.loopValue;
146
+ }
147
+ set loop(e) {
148
+ this.loopValue = !!e, this.kind === "buffer" && this.source && (this.source.loop = this.loopValue), this.media && (this.media.loop = this.loopValue);
149
+ }
150
+ get loopStart() {
151
+ return this.loopStartValue;
152
+ }
153
+ set loopStart(e) {
154
+ this.loopStartValue = d(e, "loopStart", 0), this.kind === "buffer" && this.source && (this.source.loopStart = e);
155
+ }
156
+ get loopEnd() {
157
+ return this.loopEndValue;
158
+ }
159
+ set loopEnd(e) {
160
+ this.loopEndValue = d(e, "loopEnd", 0), this.kind === "buffer" && this.source && (this.source.loopEnd = this.nodeLoopEnd);
161
+ }
162
+ get nodeLoopEnd() {
163
+ return this.loopEndValue > 0 ? this.loopEndValue : this.buffer?.duration ?? 0;
164
+ }
165
+ get playbackRate() {
166
+ return this.rateValue;
167
+ }
168
+ set playbackRate(e) {
169
+ d(e, "playbackRate"), e = i.get(this)?.apply(e) ?? e, this.kind === "buffer" && this.playing && this.source && (this.foldProgress(), n(this.source.playbackRate, e, this.context, this.listener.smoothing)), this.rateValue = e, this.media && (this.media.playbackRate = e);
170
+ }
171
+ get detune() {
172
+ return this.detuneValue;
173
+ }
174
+ set detune(e) {
175
+ d(e, "detune");
176
+ let t = this.kind === "buffer" ? this.source : null;
177
+ t && this.playing && this.foldProgress(), this.detuneValue = e, t?.detune && n(t.detune, e, this.context, this.listener.smoothing);
178
+ }
179
+ get speed() {
180
+ return this.rateValue * 2 ** (this.detuneValue / 1200);
181
+ }
182
+ foldProgress() {
183
+ let e = this.context.currentTime;
184
+ this.progress += Math.max(e - this.startedAt, 0) * this.speed, this.startedAt = Math.max(e, this.startedAt);
185
+ }
186
+ get offset() {
187
+ return this.offsetValue;
188
+ }
189
+ set offset(e) {
190
+ this.offsetValue = d(e, "offset", 0);
191
+ }
192
+ get duration() {
193
+ return this.durationValue;
194
+ }
195
+ set duration(e) {
196
+ this.durationValue = e === void 0 ? void 0 : d(e, "duration", 0);
197
+ }
198
+ get timelineStart() {
199
+ return this.timelineStartValue;
200
+ }
201
+ set timelineStart(e) {
202
+ this.timelineStartValue = d(e, "timelineStart");
203
+ }
204
+ get currentTime() {
205
+ if (this.media) return this.media.currentTime;
206
+ if (!this.buffer) return 0;
207
+ let e = this.playing ? Math.max(this.context.currentTime - this.startedAt, 0) * this.speed : 0;
208
+ return this.playhead(this.buffer.duration, this.progress + e);
209
+ }
210
+ update(e) {}
211
+ dispose() {
212
+ if (!this.disposed) {
213
+ this.stop(), this.replaceSource();
214
+ for (let e of this.filterList) u(e);
215
+ this.filterList = [], u(this.fade), u(this.gain), this.disposed = !0, this.listener.removeSource(this);
216
+ }
217
+ }
218
+ [Symbol.dispose ?? Symbol()]() {
219
+ this.dispose();
220
+ }
221
+ get head() {
222
+ return this.filterList[0] ?? this.fade;
223
+ }
224
+ setMuted(e) {
225
+ e !== this.muted && (this.muted = e, this.writeGain());
226
+ }
227
+ get isMuted() {
228
+ return this.muted;
229
+ }
230
+ get isSourceConnected() {
231
+ return this.kind === "media" || (this.kind === "buffer" ? this.source !== null : this.playing);
232
+ }
233
+ writeGain() {
234
+ n(this.gain.gain, this.muted ? 0 : this.volumeValue, this.context, this.listener.smoothing);
235
+ }
236
+ setFade(e) {
237
+ let t = this.context.currentTime;
238
+ this.fade.gain.cancelScheduledValues(t), this.fade.gain.setValueAtTime(e, t);
239
+ }
240
+ assertLive() {
241
+ if (this.disposed) throw e("disposed", "Audio is disposed; create a new Audio");
242
+ }
243
+ clearTimer() {
244
+ this.fadeTimer !== void 0 && (clearTimeout(this.fadeTimer), this.fadeTimer = void 0);
245
+ }
246
+ playhead(e, t = this.progress) {
247
+ let n = this.offsetValue + t;
248
+ if (!this.loopValue) return Math.min(Math.max(n, 0), e);
249
+ let r = this.loopStartValue, i = this.loopEndValue > 0 ? Math.min(this.loopEndValue, e) : e;
250
+ return i > r ? n < i ? n : r + (n - r) % (i - r) : e > 0 ? n % e : n;
251
+ }
252
+ startBuffer(e) {
253
+ let t = this.buffer, r = this.context;
254
+ this.stopNode();
255
+ let i = r.createBufferSource(), a = this.playhead(t.duration), o = this.loopValue || this.durationValue === void 0 ? void 0 : Math.max(0, this.durationValue - Math.max(0, a - this.offsetValue)), s = !this.loopValue && (a >= t.duration || o === 0);
256
+ i.connect(this.head), this.progress = a - this.offsetValue, this.startedAt = e, i.onended = () => this.nodeEnded(i), this.source = i, s ? (i.buffer = r.createBuffer(1, 1, r.sampleRate), i.start(e)) : (i.buffer = t, i.loop = this.loopValue, i.loopStart = this.loopStartValue, i.loopEnd = this.nodeLoopEnd, n(i.playbackRate, this.rateValue, r, 0, !0), n(i.detune, this.detuneValue, r, 0, !0), o === void 0 ? i.start(e, a) : i.start(e, a, o));
257
+ }
258
+ nodeEnded(e) {
259
+ u(e), e === this.source && (this.source = null, this.playing && (this.playing = !1, this.endedNaturally = !0, this.progress = 0, this.onEnded?.(this)));
260
+ }
261
+ stopNode(e = 0) {
262
+ let t = this.source;
263
+ if (t && this.kind === "buffer") {
264
+ if (e > 0) t.stop(this.context.currentTime + e);
265
+ else {
266
+ t.onended = null;
267
+ try {
268
+ t.stop();
269
+ } catch {}
270
+ u(t), this.source = null;
271
+ }
272
+ }
273
+ }
274
+ haltOther(e) {
275
+ this.kind === "media" && this.media ? (this.media.pause(), e && (this.media.currentTime = this.offsetValue)) : (this.kind === "stream" || this.kind === "node") && this.source && u(this.source, this.head);
276
+ }
277
+ replaceSource() {
278
+ this.clearTimer(), this.kind === "buffer" ? this.stopNode() : this.kind === "media" && this.media ? (this.media.pause(), this.media.removeEventListener("ended", this.onMediaEnded), u(this.source, this.head)) : this.source && u(this.source, this.head), this.playing = !1, this.endedNaturally = !1, this.kind = null, this.source = null, this.media = null, this.buffer = null, this.progress = 0;
279
+ }
280
+ }, p = class extends f {
281
+ constructor(e, t = {}) {
282
+ let n = e.context.createPanner();
283
+ super(e, {
284
+ ...t,
285
+ filters: void 0
286
+ }), this.worldPosition = /* @__PURE__ */ new Float64Array(3), this.worldDirection = new Float64Array([
287
+ 0,
288
+ 0,
289
+ 1
290
+ ]), this.meshValue = null, this.localDirection = new Float64Array([
291
+ 0,
292
+ 0,
293
+ 1
294
+ ]), this.directionScratch = /* @__PURE__ */ new Float64Array(3), this.written = !1, this.panner = n;
295
+ try {
296
+ this.gain.connect(n), n.connect(e.input), n.panningModel = t.panningModel ?? "HRTF", this.distanceModel = t.distanceModel ?? "inverse", this.refDistance = t.refDistance ?? 1, this.maxDistance = t.maxDistance ?? 1e4, this.rolloffFactor = t.rolloffFactor ?? 1, this.setDirectionalCone(t.coneInnerAngle ?? 360, t.coneOuterAngle ?? 360, t.coneOuterGain ?? 0), this.muteWhenHidden = t.muteWhenHidden ?? !1, t.direction && this.setDirection(t.direction), t.filters?.length && this.setFilters(t.filters), t.mesh && this.attach(t.mesh), this.writePose();
297
+ } catch (e) {
298
+ throw this.dispose(), e;
299
+ }
300
+ }
301
+ getOutput() {
302
+ return this.panner ?? this.gain;
303
+ }
304
+ connectOutput() {}
305
+ get panningModel() {
306
+ return this.panner.panningModel;
307
+ }
308
+ set panningModel(e) {
309
+ this.panner.panningModel = e;
310
+ }
311
+ get distanceModel() {
312
+ return this.panner.distanceModel;
313
+ }
314
+ set distanceModel(e) {
315
+ if (e !== "linear" && e !== "inverse" && e !== "exponential") throw TypeError(`Unknown distance model ${String(e)}; use 'linear', 'inverse' or 'exponential'`);
316
+ this.panner.distanceModel = e;
317
+ }
318
+ get refDistance() {
319
+ return this.panner.refDistance;
320
+ }
321
+ set refDistance(e) {
322
+ this.panner.refDistance = d(e, "refDistance", 0);
323
+ }
324
+ get maxDistance() {
325
+ return this.panner.maxDistance;
326
+ }
327
+ set maxDistance(e) {
328
+ if (d(e, "maxDistance") <= 0) throw RangeError("maxDistance must be > 0");
329
+ this.panner.maxDistance = e;
330
+ }
331
+ get rolloffFactor() {
332
+ return this.panner.rolloffFactor;
333
+ }
334
+ set rolloffFactor(e) {
335
+ this.panner.rolloffFactor = d(e, "rolloffFactor", 0);
336
+ }
337
+ setDirectionalCone(e, t, n) {
338
+ if (d(e, "coneInnerAngle"), d(t, "coneOuterAngle"), d(n, "coneOuterGain") < 0 || n > 1) throw RangeError("coneOuterGain must be 0..1");
339
+ return this.panner.coneInnerAngle = e, this.panner.coneOuterAngle = t, this.panner.coneOuterGain = n, this;
340
+ }
341
+ get mesh() {
342
+ return this.meshValue;
343
+ }
344
+ attach(e) {
345
+ return this.meshValue = e, this;
346
+ }
347
+ detach() {
348
+ return this.attach(null);
349
+ }
350
+ setPosition(e, t, n) {
351
+ return d(e, "x"), d(t, "y"), d(n, "z"), this.meshValue = null, this.worldPosition[0] = e, this.worldPosition[1] = t, this.worldPosition[2] = n, this.writePose(), this;
352
+ }
353
+ setDirection(e) {
354
+ let t = this.directionScratch;
355
+ if (!r(e[0], e[1], e[2], t, c)) throw RangeError("Direction must be nonzero");
356
+ return this.localDirection.set(t), this.meshValue || (this.worldDirection.set(t), this.panner && this.writePose()), this;
357
+ }
358
+ update(e) {
359
+ let t = this.meshValue;
360
+ if (!t || !e) return;
361
+ let n = a(e), i = o(t).id;
362
+ if (n.meshes.get(i) !== t) return;
363
+ let l = n.store, u = l.matrices, d = i * 16, [f, p, m] = this.localDirection, h = u[d + 12], g = u[d + 13], _ = u[d + 14], v = this.directionScratch;
364
+ r(u[d] * f + u[d + 4] * p + u[d + 8] * m, u[d + 1] * f + u[d + 5] * p + u[d + 9] * m, u[d + 2] * f + u[d + 6] * p + u[d + 10] * m, v, c), Number.isFinite(h) && Number.isFinite(g) && Number.isFinite(_) && (h !== this.worldPosition[0] || g !== this.worldPosition[1] || _ !== this.worldPosition[2] || v[0] !== this.worldDirection[0] || v[1] !== this.worldDirection[1] || v[2] !== this.worldDirection[2]) && (this.worldPosition[0] = h, this.worldPosition[1] = g, this.worldPosition[2] = _, this.worldDirection.set(v), this.writePose()), this.setMuted(this.muteWhenHidden && s(l, i));
365
+ }
366
+ dispose() {
367
+ super.dispose(), u(this.panner), this.meshValue = null;
368
+ }
369
+ [Symbol.dispose ?? Symbol()]() {
370
+ this.dispose();
371
+ }
372
+ writePose() {
373
+ let e = this.panner, t = this.context, r = !this.written, i = this.listener.smoothing;
374
+ this.written = !0;
375
+ let a = this.worldPosition[0], o = this.worldPosition[1], s = this.worldPosition[2], c = this.worldDirection[0], l = this.worldDirection[1], u = this.worldDirection[2];
376
+ e.positionX ? (n(e.positionX, a, t, i, r), n(e.positionY, o, t, i, r), n(e.positionZ, s, t, i, r), n(e.orientationX, c, t, i, r), n(e.orientationY, l, t, i, r), n(e.orientationZ, u, t, i, r)) : (e.setPosition(a, o, s), e.setOrientation(c, l, u));
377
+ }
378
+ }, m = class {
379
+ constructor(e, t, n = {}) {
380
+ this.listener = e, this.buffer = t, this.plays = 0, this.disposed = !1;
381
+ let { voices: r = 8, ...i } = n;
382
+ if (!Number.isSafeInteger(r) || r < 1) throw RangeError(`AudioVoicePool voices is ${r}; pass a whole number of 1 or more`);
383
+ if (typeof t?.duration != "number") throw TypeError("AudioVoicePool needs a decoded AudioBuffer; pass the result of listener.load(url)");
384
+ this.volume = i.volume ?? 1, this.playbackRate = i.playbackRate ?? 1;
385
+ let a = [];
386
+ try {
387
+ for (let n = 0; n < r; n++) a.push(new p(e, i).setBuffer(t));
388
+ } catch (e) {
389
+ for (let e of a) e.dispose();
390
+ throw e;
391
+ }
392
+ this.voices = a, this.started = a.map(() => 0);
393
+ }
394
+ play(n, r = {}) {
395
+ if (this.disposed) throw e("disposed", "AudioVoicePool is disposed; create a new AudioVoicePool");
396
+ let a = r.volume ?? this.volume, o = r.playbackRate ?? this.playbackRate;
397
+ if (n.length !== 3 || !Number.isFinite(n[0]) || !Number.isFinite(n[1]) || !Number.isFinite(n[2])) throw t("AudioVoicePool position needs three finite coordinates; pass [x, y, z] in metres", "state");
398
+ if (!Number.isFinite(a) || a < 0 || !Number.isFinite(o)) throw t("AudioVoicePool needs finite playbackRate and nonnegative finite volume; pass valid play options", "state");
399
+ let s = this.voices.findIndex((e) => !e.isPlaying);
400
+ s < 0 && (s = this.started.indexOf(Math.min(...this.started)));
401
+ let c = this.voices[s], l = this.listener, u = l.smoothing;
402
+ i.get(c)?.validate(o), c.stop(), l.smoothing = 0;
403
+ try {
404
+ c.setPosition(n[0], n[1], n[2]), c.volume = a, c.playbackRate = o;
405
+ } finally {
406
+ l.smoothing = u;
407
+ }
408
+ return this.started[s] = ++this.plays, c.play();
409
+ }
410
+ stopAll() {
411
+ for (let e of this.voices) e.stop();
412
+ return this;
413
+ }
414
+ dispose() {
415
+ if (!this.disposed) {
416
+ this.disposed = !0;
417
+ for (let e of this.voices) e.dispose();
418
+ }
419
+ }
420
+ [Symbol.dispose ?? Symbol()]() {
421
+ this.dispose();
422
+ }
423
+ };
424
+ //#endregion
425
+ export { f as n, p as r, m as t };
@@ -0,0 +1,45 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import { PositionalAudio, type PositionalAudioOptions } from './audio.js';
3
+ import type { AudioListener } from './listener.js';
4
+ import type { Vec3 } from './math.js';
5
+ /**
6
+ * Options of {@link AudioVoicePool}: the {@link PositionalAudioOptions} every voice shares (distance model, cone,
7
+ * volume, playbackRate...), plus how many voices there are. Voices take no mesh, autoplay or filter chain.
8
+ */
9
+ export interface AudioVoicePoolOptions extends Omit<PositionalAudioOptions, 'mesh' | 'autoplay' | 'filters'> {
10
+ /** Voices that can sound at once, default 8. A play while every voice sounds steals the oldest. */
11
+ voices?: number;
12
+ }
13
+ /**
14
+ * Overlapping one-shot sounds from one decoded buffer, such as footsteps, block breaks and hits: `voices`
15
+ * {@link PositionalAudio} voices share the buffer. Each {@link AudioVoicePool.play} takes a voice that is not sounding
16
+ * or, when every voice sounds, steals the one that started longest ago (cut off at once). A voice jumps to its new
17
+ * position and level, never easing from the previous play's.
18
+ */
19
+ export declare class AudioVoicePool {
20
+ readonly listener: AudioListener;
21
+ readonly buffer: AudioBuffer;
22
+ /** The voices, in creation order. */
23
+ readonly voices: readonly PositionalAudio[];
24
+ /** Start order of each voice (0 = never played), so the oldest is the lowest. */
25
+ private readonly started;
26
+ private plays;
27
+ private readonly volume;
28
+ private readonly playbackRate;
29
+ private disposed;
30
+ constructor(listener: AudioListener, buffer: AudioBuffer, options?: AudioVoicePoolOptions);
31
+ /**
32
+ * Plays the buffer once at world `position` on a free voice, or steals the voice that started longest ago.
33
+ * `volume` and `playbackRate` (pitch: vary it a little per play for footsteps and block sounds) apply to this play
34
+ * only and default to the pool's options. Returns the voice, which can be stopped or moved while it sounds.
35
+ */
36
+ play(position: Vec3, options?: {
37
+ volume?: number;
38
+ playbackRate?: number;
39
+ }): PositionalAudio;
40
+ /** Stops every voice. */
41
+ stopAll(): this;
42
+ /** Stops and disposes every voice. The buffer stays usable (the listener's load cache may share it). */
43
+ dispose(): void;
44
+ [Symbol.dispose]: () => void;
45
+ }
package/dist/wav.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ /** How a file stores each sample. `pcm8` is unsigned; the other integer formats are signed. */
2
+ export type WavSampleFormat = 'pcm8' | 'pcm16' | 'pcm24' | 'pcm32' | 'float32' | 'float64';
3
+ /** Decoded audio: one Float32Array per channel, samples nominally in -1..1. */
4
+ export interface WavAudio {
5
+ /** Frames per second, a positive integer. */
6
+ sampleRate: number;
7
+ /** One array per channel, all the same length. */
8
+ channels: Float32Array[];
9
+ /** The sample format of the file the audio was read from. */
10
+ format: WavSampleFormat;
11
+ /** The speaker bits of a WAVE_FORMAT_EXTENSIBLE file (bit 0 front left, bit 1 front right, bit 2 front centre, ...); 0 when absent or unspecified. */
12
+ channelMask: number;
13
+ }
14
+ /** What `encodeWav` needs: a rate and the channels (typed arrays or plain number arrays, all the same length). */
15
+ export interface WavInput {
16
+ sampleRate: number;
17
+ channels: ArrayLike<number>[];
18
+ /** The speaker bits written to an extensible header. Default: the usual layout for 1, 2, 4, 6 and 8 channels, else 0. */
19
+ channelMask?: number;
20
+ }
21
+ /** Options of `encodeWav`. */
22
+ export interface EncodeWavOptions {
23
+ /** Default `pcm16`. */
24
+ format?: WavSampleFormat;
25
+ }
26
+ /**
27
+ * Reads a RIFF WAVE file: 8, 16, 24 and 32-bit integer PCM and 32 and 64-bit float, plain or WAVE_FORMAT_EXTENSIBLE,
28
+ * with any number of channels. Chunks other than `fmt ` and `data` (`LIST`, `bext`, `iXML`, `cue `) are skipped. A
29
+ * `data` size that is 0xFFFFFFFF, or runs past the end of the file (a file still being written), reads to the end; a
30
+ * last partial frame is dropped. Integer samples become `value / 2^(bits - 1)` (8-bit: `(byte - 128) / 128`), so
31
+ * `encodeWav` of the result in the same format returns the same samples.
32
+ * @example
33
+ * const audio = decodeWav(bytes); // bytes: the file as a Uint8Array or ArrayBuffer
34
+ * console.log(audio.sampleRate, audio.channels.length, audio.channels[0].length);
35
+ */
36
+ export declare function decodeWav(data: ArrayBuffer | ArrayBufferView): WavAudio;
37
+ /**
38
+ * Writes a RIFF WAVE file. Integer formats scale by `2^(bits - 1)`, round to nearest and clamp to the format's range
39
+ * (so 1 becomes the largest value, no wrap); float formats store the samples as they are. Files with more than two
40
+ * channels, or 24 or 32-bit integer or 64-bit float samples, use WAVE_FORMAT_EXTENSIBLE as the Microsoft guidance for
41
+ * multichannel and wide files says; the rest use the plain header every tool reads. NaN becomes 0 in integer formats.
42
+ * @example
43
+ * const left = new Float32Array(48_000).map((_, i) => Math.sin((2 * Math.PI * 440 * i) / 48_000) * 0.5);
44
+ * const file = encodeWav({sampleRate: 48_000, channels: [left, left]}, {format: 'pcm24'}); // a Uint8Array
45
+ * console.log(file.byteLength);
46
+ */
47
+ export declare function encodeWav(audio: WavInput, options?: EncodeWavOptions): Uint8Array;
package/dist/wav.js ADDED
@@ -0,0 +1,156 @@
1
+ import { i as e, r as t, t as n } from "./errors-D8rc8kzg.js";
2
+ //#region src/wav.ts
3
+ var r = {
4
+ pcm8: 8,
5
+ pcm16: 16,
6
+ pcm24: 24,
7
+ pcm32: 32,
8
+ float32: 32,
9
+ float64: 64
10
+ }, i = 1, a = 3, o = 65534, s = [
11
+ 0,
12
+ 0,
13
+ 0,
14
+ 0,
15
+ 16,
16
+ 0,
17
+ 128,
18
+ 0,
19
+ 0,
20
+ 170,
21
+ 0,
22
+ 56,
23
+ 155,
24
+ 113
25
+ ], c = {
26
+ 1: 4,
27
+ 2: 3,
28
+ 4: 51,
29
+ 6: 63,
30
+ 8: 1599
31
+ }, l = (e, t) => n(e, t, "wav"), u = (e, t) => String.fromCharCode(e.getUint8(t), e.getUint8(t + 1), e.getUint8(t + 2), e.getUint8(t + 3));
32
+ function d(t) {
33
+ if (t instanceof ArrayBuffer) return new Uint8Array(t);
34
+ if (ArrayBuffer.isView(t)) return new Uint8Array(t.buffer, t.byteOffset, t.byteLength);
35
+ throw e("decodeWav needs an ArrayBuffer or a typed array holding the file; read the file into bytes first", "wav");
36
+ }
37
+ function f(e, t) {
38
+ if (e === i) {
39
+ if (t === 8) return "pcm8";
40
+ if (t === 16) return "pcm16";
41
+ if (t === 24) return "pcm24";
42
+ if (t === 32) return "pcm32";
43
+ }
44
+ if (e === a) {
45
+ if (t === 32) return "float32";
46
+ if (t === 64) return "float64";
47
+ }
48
+ throw l("unsupported", `WAV format tag ${e} with ${t} bits per sample is not supported; read 8, 16, 24 and 32-bit PCM and 32 and 64-bit float, or convert the file first`);
49
+ }
50
+ function p(e) {
51
+ let t = d(e), n = new DataView(t.buffer, t.byteOffset, t.byteLength);
52
+ if (t.length < 12) throw l("failed", "Not a WAV file: shorter than the 12-byte RIFF header");
53
+ let r = u(n, 0);
54
+ if (r === "RF64" || r === "BW64") throw l("unsupported", "RF64 and BW64 files (over 4 GiB) are not supported; split the audio into files under 4 GiB");
55
+ if (r !== "RIFF" || u(n, 8) !== "WAVE") throw l("failed", "Not a WAV file: it must start with RIFF and form type WAVE");
56
+ let i, a = -1, c = 0;
57
+ for (let e = 12; e + 8 <= t.length;) {
58
+ let r = u(n, e), d = n.getUint32(e + 4, !0), f = e + 8;
59
+ if (r === "fmt ") {
60
+ if (d < 16 || f + 16 > t.length) throw l("failed", "The WAV fmt chunk is shorter than 16 bytes");
61
+ let e = n.getUint16(f, !0), r = 0, a = n.getUint16(f + 14, !0);
62
+ if (e === o) {
63
+ if (d < 40 || f + 40 > t.length) throw l("failed", "The WAV extensible fmt chunk is shorter than 40 bytes");
64
+ if (n.getUint16(f + 16, !0) < 22) throw l("failed", "The WAV extensible fmt chunk has no 22-byte extension");
65
+ r = n.getUint32(f + 20, !0), e = n.getUint16(f + 24, !0);
66
+ for (let e = 0; e < s.length; e++) if (n.getUint8(f + 26 + e) !== s[e]) throw l("unsupported", "The WAV extensible SubFormat is not PCM or IEEE float; convert the file first");
67
+ }
68
+ i = {
69
+ tag: e,
70
+ channels: n.getUint16(f + 2, !0),
71
+ rate: n.getUint32(f + 4, !0),
72
+ bits: a,
73
+ mask: r
74
+ };
75
+ let c = n.getUint16(f + 12, !0);
76
+ if (i.channels < 1 || i.rate < 1) throw l("failed", "The WAV fmt chunk has no channels or a zero sample rate");
77
+ if (a === 0 || a % 8 || c !== i.channels * a / 8) throw l("failed", `The WAV fmt chunk is inconsistent: ${a} bits per sample, ${i.channels} channels, block align ${c}`);
78
+ } else if (r === "data" && a < 0 && (a = f, c = d === 4294967295 || f + d > t.length ? t.length - f : d, i)) break;
79
+ d += d & 1, e = f + d;
80
+ }
81
+ if (!i) throw l("failed", "The WAV file has no fmt chunk");
82
+ if (a < 0) throw l("failed", "The WAV file has no data chunk");
83
+ let p = f(i.tag, i.bits), m = i.bits / 8, h = Math.floor(c / (m * i.channels)), g = Array.from({ length: i.channels }, () => new Float32Array(h));
84
+ for (let e = 0, t = a; e < h; e++) for (let r = 0; r < i.channels; r++, t += m) {
85
+ let i;
86
+ switch (p) {
87
+ case "pcm8":
88
+ i = (n.getUint8(t) - 128) / 128;
89
+ break;
90
+ case "pcm16":
91
+ i = n.getInt16(t, !0) / 32768;
92
+ break;
93
+ case "pcm24":
94
+ i = (n.getUint8(t) | n.getUint8(t + 1) << 8 | n.getInt8(t + 2) << 16) / 8388608;
95
+ break;
96
+ case "pcm32":
97
+ i = n.getInt32(t, !0) / 2147483648;
98
+ break;
99
+ case "float32":
100
+ i = n.getFloat32(t, !0);
101
+ break;
102
+ default: i = n.getFloat64(t, !0);
103
+ }
104
+ g[r][e] = i;
105
+ }
106
+ return {
107
+ sampleRate: i.rate,
108
+ channels: g,
109
+ format: p,
110
+ channelMask: i.mask
111
+ };
112
+ }
113
+ function m(e, n = {}) {
114
+ let l = n.format ?? "pcm16";
115
+ if (!(l in r)) throw t(`Unknown WAV format ${String(l)}; use pcm8, pcm16, pcm24, pcm32, float32 or float64`, "wav");
116
+ let { sampleRate: u, channels: d } = e;
117
+ if (!Number.isInteger(u) || u < 1 || u > 4294967295) throw t("encodeWav needs an integer sampleRate from 1 to 4294967295", "wav");
118
+ if (!Array.isArray(d) || d.length < 1 || d.length > 65535) throw t("encodeWav needs from 1 to 65535 channels, each an array of samples", "wav");
119
+ let f = d[0]?.length;
120
+ if (!Number.isInteger(f) || d.some((e) => !e || e.length !== f)) throw t("encodeWav needs every channel to be an array of the same length", "wav");
121
+ let p = d.length, m = r[l], h = m / 8, g = l === "float32" || l === "float64", _ = p > 2 || l === "pcm24" || l === "pcm32" || l === "float64", v = _ ? 60 : 36, y = f * p * h, b = y & 1;
122
+ if (v + y + b > 4294967295) throw t("A WAV file holds under 4 GiB; split the audio into shorter files", "wav");
123
+ let x = new Uint8Array(v + 8 + y + b), S = new DataView(x.buffer), C = (e, t) => {
124
+ for (let n = 0; n < 4; n++) x[e + n] = t.charCodeAt(n);
125
+ };
126
+ C(0, "RIFF"), S.setUint32(4, x.length - 8, !0), C(8, "WAVE"), C(12, "fmt "), S.setUint32(16, _ ? 40 : 16, !0), S.setUint16(20, _ ? o : g ? a : i, !0), S.setUint16(22, p, !0), S.setUint32(24, u, !0), S.setUint32(28, u * p * h, !0), S.setUint16(32, p * h, !0), S.setUint16(34, m, !0);
127
+ let w;
128
+ _ && (S.setUint16(36, 22, !0), S.setUint16(38, m, !0), S.setUint32(40, e.channelMask ?? c[p] ?? 0, !0), S.setUint16(44, g ? a : i, !0), x.set(s, 46)), w = v, C(w, "data"), S.setUint32(w + 4, y, !0), w += 8;
129
+ let T = (e, t, n) => Math.min(n, Math.max(t, Math.round(e) || 0));
130
+ for (let e = 0; e < f; e++) for (let t = 0; t < p; t++, w += h) {
131
+ let n = d[t][e];
132
+ switch (l) {
133
+ case "pcm8":
134
+ S.setUint8(w, T(n * 128, -128, 127) + 128);
135
+ break;
136
+ case "pcm16":
137
+ S.setInt16(w, T(n * 32768, -32768, 32767), !0);
138
+ break;
139
+ case "pcm24": {
140
+ let e = T(n * 8388608, -8388608, 8388607);
141
+ S.setUint8(w, e & 255), S.setUint8(w + 1, e >> 8 & 255), S.setUint8(w + 2, e >> 16 & 255);
142
+ break;
143
+ }
144
+ case "pcm32":
145
+ S.setInt32(w, T(n * 2147483648, -2147483648, 2147483647), !0);
146
+ break;
147
+ case "float32":
148
+ S.setFloat32(w, n, !0);
149
+ break;
150
+ default: S.setFloat64(w, n, !0);
151
+ }
152
+ }
153
+ return x;
154
+ }
155
+ //#endregion
156
+ export { p as decodeWav, m as encodeWav };