@schmooky/zvuk 1.9.0 → 1.11.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/dist/index.d.ts +181 -12
- package/dist/index.js +195 -21
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -238,10 +238,27 @@ interface VoiceDefaults {
|
|
|
238
238
|
*/
|
|
239
239
|
stopFade?: number;
|
|
240
240
|
}
|
|
241
|
-
interface EngineConfig {
|
|
242
|
-
buses?: Record<
|
|
241
|
+
interface EngineConfig<TBusName extends string = string> {
|
|
242
|
+
buses?: Record<TBusName, BusConfig>;
|
|
243
243
|
master?: MasterConfig;
|
|
244
244
|
voice?: VoiceDefaults;
|
|
245
|
+
/**
|
|
246
|
+
* Hint to the underlying `AudioContext` about the desired latency /
|
|
247
|
+
* battery trade-off. Maps to `AudioContextOptions.latencyHint`:
|
|
248
|
+
*
|
|
249
|
+
* - `'interactive'` — the default Web Audio behaviour. Right call for
|
|
250
|
+
* game audio, slot machines, anything where 60 fps reactive sound
|
|
251
|
+
* matters more than power consumption.
|
|
252
|
+
* - `'playback'` — longer buffers, lower CPU, higher latency. Right
|
|
253
|
+
* call for music players, podcasting tools, anything where the user
|
|
254
|
+
* isn't expecting input-to-sound to feel "instant."
|
|
255
|
+
* - `'balanced'` — the browser picks.
|
|
256
|
+
* - A number — explicit latency in seconds. Browsers honour it on a
|
|
257
|
+
* best-effort basis.
|
|
258
|
+
*
|
|
259
|
+
* Default: undefined (the browser picks; usually `'interactive'`).
|
|
260
|
+
*/
|
|
261
|
+
latencyHint?: AudioContextLatencyCategory | number;
|
|
245
262
|
/**
|
|
246
263
|
* External ticker (e.g. Pixi `app.ticker`, GSAP `gsap.ticker`) that drives
|
|
247
264
|
* scheduler dispatch. Without one, the scheduler uses `setTimeout` —
|
|
@@ -297,15 +314,59 @@ interface StopOptions {
|
|
|
297
314
|
interface VoiceJitter {
|
|
298
315
|
jitter?: number;
|
|
299
316
|
}
|
|
317
|
+
/**
|
|
318
|
+
* Distance-attenuation curve. Mirrors `PannerNode.distanceModel`:
|
|
319
|
+
* - `'inverse'` (default) — natural-sounding rolloff, matches outdoor sound.
|
|
320
|
+
* - `'linear'` — straight-line attenuation between `refDistance` and `maxDistance`.
|
|
321
|
+
* - `'exponential'` — steeper than inverse; useful for tight environments.
|
|
322
|
+
*/
|
|
323
|
+
type DistanceModel = 'linear' | 'inverse' | 'exponential';
|
|
300
324
|
interface SpatialOptions {
|
|
301
325
|
/** [-1, 1] stereo pan (2D). Mutually exclusive with `position`. */
|
|
302
326
|
pan?: number;
|
|
303
327
|
/** [x, y, z] world-space position (3D). Mutually exclusive with `pan`. */
|
|
304
328
|
position?: [number, number, number];
|
|
329
|
+
/**
|
|
330
|
+
* Distance below which the source is at full volume. Default 1.
|
|
331
|
+
* 3D only; ignored when `pan` is used.
|
|
332
|
+
*/
|
|
333
|
+
refDistance?: number;
|
|
334
|
+
/**
|
|
335
|
+
* Distance beyond which `'linear'` attenuation reaches zero. The
|
|
336
|
+
* `'inverse'` and `'exponential'` models keep falling off but use this
|
|
337
|
+
* as the curve's anchor. Default 10000.
|
|
338
|
+
* 3D only; ignored when `pan` is used.
|
|
339
|
+
*/
|
|
340
|
+
maxDistance?: number;
|
|
341
|
+
/**
|
|
342
|
+
* How aggressively distance attenuates the sound. 1 is the natural
|
|
343
|
+
* rolloff for the chosen `distanceModel`; higher values produce a
|
|
344
|
+
* more dramatic falloff. Default 1.
|
|
345
|
+
* 3D only; ignored when `pan` is used.
|
|
346
|
+
*/
|
|
347
|
+
rolloffFactor?: number;
|
|
348
|
+
/** Distance-attenuation curve. Default `'inverse'`. 3D only. */
|
|
349
|
+
distanceModel?: DistanceModel;
|
|
350
|
+
/**
|
|
351
|
+
* Occlusion amount (0..1). Drives an internal low-pass filter that
|
|
352
|
+
* sweeps cutoff from 22050 Hz (transparent) down to ~500 Hz (heavily
|
|
353
|
+
* muffled), plus a small gain dip — the standard "behind a wall"
|
|
354
|
+
* effect. Independent of distance attenuation; combine via a
|
|
355
|
+
* `Parameter` if you want one knob to drive both.
|
|
356
|
+
* 3D only; ignored when `pan` is used.
|
|
357
|
+
*/
|
|
358
|
+
occlusion?: number;
|
|
305
359
|
}
|
|
306
360
|
interface PlayOptions {
|
|
307
361
|
/** Initial volume (0..1). Default 1. */
|
|
308
362
|
volume?: number | VoiceJitter;
|
|
363
|
+
/**
|
|
364
|
+
* Fade-in duration (seconds) applied to the voice's gain at start.
|
|
365
|
+
* Default 0 (instant). Convenience for "drop in smoothly" — the dual
|
|
366
|
+
* of the click-free stop fade. Equivalent to playing at `volume: 0`
|
|
367
|
+
* and immediately calling `voice.fade({ to: volume, duration: fadeIn })`.
|
|
368
|
+
*/
|
|
369
|
+
fadeIn?: number;
|
|
309
370
|
/** Playback rate. 1 = source speed. Random jitter optional. */
|
|
310
371
|
pitch?: number | VoiceJitter;
|
|
311
372
|
/** Loop the voice. Default false. */
|
|
@@ -447,18 +508,43 @@ interface PreloadOptions {
|
|
|
447
508
|
}
|
|
448
509
|
|
|
449
510
|
/**
|
|
450
|
-
* PannerNode wrapper. Inserted between a Voice and
|
|
451
|
-
* passes a `spatializer` option.
|
|
452
|
-
*
|
|
453
|
-
*
|
|
511
|
+
* PannerNode + occlusion biquad wrapper. Inserted between a Voice and
|
|
512
|
+
* its Bus when a play call passes a `spatializer` option.
|
|
513
|
+
*
|
|
514
|
+
* - 2D pan uses `StereoPannerNode` (cheap, just left/right shift).
|
|
515
|
+
* - 3D uses `PannerNode` in HRTF mode (one node per voice — fine for
|
|
516
|
+
* the dozens of simultaneous voices a typical game holds, expensive
|
|
517
|
+
* past hundreds), followed by a biquad lowpass for occlusion plus a
|
|
518
|
+
* gain stage so occlusion can also drop level slightly.
|
|
519
|
+
*
|
|
520
|
+
* 3D config (`refDistance`, `maxDistance`, `rolloffFactor`,
|
|
521
|
+
* `distanceModel`) is configurable per voice via `SpatialOptions` and
|
|
522
|
+
* tunable live via the `set*` methods. Occlusion is a single 0..1 knob
|
|
523
|
+
* that drives the lowpass cutoff plus a small gain dip.
|
|
454
524
|
*/
|
|
455
525
|
declare class Spatializer {
|
|
456
|
-
private
|
|
526
|
+
private ctx;
|
|
457
527
|
private kind;
|
|
528
|
+
private input;
|
|
529
|
+
private output;
|
|
530
|
+
private stereoPan;
|
|
531
|
+
private panner;
|
|
532
|
+
private occlusionFilter;
|
|
533
|
+
private occlusionGain;
|
|
458
534
|
constructor(ctx: AudioContext, opts: SpatialOptions);
|
|
459
535
|
setPan(pan: number): void;
|
|
460
536
|
setPosition(x: number, y: number, z: number): void;
|
|
461
|
-
|
|
537
|
+
setRefDistance(d: number): void;
|
|
538
|
+
setMaxDistance(d: number): void;
|
|
539
|
+
setRolloffFactor(f: number): void;
|
|
540
|
+
setDistanceModel(m: DistanceModel): void;
|
|
541
|
+
/**
|
|
542
|
+
* Set occlusion amount (0..1). Drives the internal lowpass cutoff
|
|
543
|
+
* and a small gain dip — independent of distance attenuation.
|
|
544
|
+
* No-op on 2D spatializers.
|
|
545
|
+
*/
|
|
546
|
+
setOcclusion(amount: number): void;
|
|
547
|
+
/** Connects the spatializer's output into `dest` and returns the input the Voice should use. */
|
|
462
548
|
connectInto(dest: AudioNode): AudioNode;
|
|
463
549
|
dispose(): void;
|
|
464
550
|
private setPanner3D;
|
|
@@ -1180,6 +1266,45 @@ declare class StreamSound {
|
|
|
1180
1266
|
dispose(): void;
|
|
1181
1267
|
}
|
|
1182
1268
|
|
|
1269
|
+
/**
|
|
1270
|
+
* Strategy for picking which variant fires on each `play()`:
|
|
1271
|
+
*
|
|
1272
|
+
* - `'random'` — uniform random pick. Cheap; can play the same one twice
|
|
1273
|
+
* in a row, which sounds robotic.
|
|
1274
|
+
* - `'no-repeat'` (default) — uniform random, but never the same as the
|
|
1275
|
+
* previous pick. The fix every casino slot uses for SFX variants.
|
|
1276
|
+
* - `'shuffle-bag'` — Tetris-style: cycle through every variant in a
|
|
1277
|
+
* random shuffle, then reshuffle once the bag empties. Guarantees
|
|
1278
|
+
* every variant gets played roughly equally.
|
|
1279
|
+
*/
|
|
1280
|
+
type VariantStrategy = 'random' | 'no-repeat' | 'shuffle-bag';
|
|
1281
|
+
interface VariantsOptions {
|
|
1282
|
+
strategy?: VariantStrategy;
|
|
1283
|
+
}
|
|
1284
|
+
/**
|
|
1285
|
+
* A bundle of N alternate sounds that play one at a time. The classic
|
|
1286
|
+
* casino-slot pattern: every coin / win / reel-stop trigger plays a
|
|
1287
|
+
* randomised variant so stacked SFX don't sound robotic.
|
|
1288
|
+
*
|
|
1289
|
+
* Construct via `engine.loadVariants(name, urlSets)`; spawn voices via
|
|
1290
|
+
* `engine.variants(name).play()`. The picker strategy is configurable
|
|
1291
|
+
* (`'random'` | `'no-repeat'` | `'shuffle-bag'`).
|
|
1292
|
+
*/
|
|
1293
|
+
declare class Variants {
|
|
1294
|
+
readonly name: string;
|
|
1295
|
+
readonly count: number;
|
|
1296
|
+
private sounds;
|
|
1297
|
+
private strategy;
|
|
1298
|
+
private lastIndex;
|
|
1299
|
+
private bag;
|
|
1300
|
+
constructor(name: string, sounds: Sound[], options?: VariantsOptions);
|
|
1301
|
+
/** Spawn a Voice on a randomly-picked variant. */
|
|
1302
|
+
play(options?: PlayOptions): Voice;
|
|
1303
|
+
/** Force the next pick to use a specific variant index. Useful for tests. */
|
|
1304
|
+
playIndex(index: number, options?: PlayOptions): Voice;
|
|
1305
|
+
private pick;
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1183
1308
|
interface SnapshotState {
|
|
1184
1309
|
buses: Record<string, {
|
|
1185
1310
|
level: number;
|
|
@@ -1209,7 +1334,13 @@ declare class Snapshot {
|
|
|
1209
1334
|
apply(opts?: ApplyOptions): Promise<void>;
|
|
1210
1335
|
}
|
|
1211
1336
|
|
|
1212
|
-
|
|
1337
|
+
/**
|
|
1338
|
+
* The audio engine. Generic in `TBusName` so that `engine.bus(name)`
|
|
1339
|
+
* type-checks against the bus names you declared in
|
|
1340
|
+
* `createEngine({ buses })`. When the buses map is inferred from a
|
|
1341
|
+
* literal, typos like `engine.bus('sxf')` fail at compile time.
|
|
1342
|
+
*/
|
|
1343
|
+
interface Engine<TBusName extends string = string> {
|
|
1213
1344
|
readonly state: EngineState;
|
|
1214
1345
|
readonly now: number;
|
|
1215
1346
|
/** Live AudioContext. Constructs one on first read. Throws if engine is closed. */
|
|
@@ -1235,6 +1366,26 @@ interface Engine {
|
|
|
1235
1366
|
* `string` URL, or `undefined`/`null` to fall through to the URL list.
|
|
1236
1367
|
*/
|
|
1237
1368
|
loadSound(name: string, url: string | readonly string[], options?: LoadSoundOptions): Promise<Sound>;
|
|
1369
|
+
/**
|
|
1370
|
+
* Load N alternate sounds and group them under a single name. The
|
|
1371
|
+
* registered `Variants` instance picks one on each `play()` according
|
|
1372
|
+
* to the configured strategy:
|
|
1373
|
+
*
|
|
1374
|
+
* - `'random'` — uniform random pick.
|
|
1375
|
+
* - `'no-repeat'` (default) — uniform random, but never the same as the
|
|
1376
|
+
* previous pick. Eliminates the robotic "click click click" feel of
|
|
1377
|
+
* stacked SFX without needing a custom shuffler.
|
|
1378
|
+
* - `'shuffle-bag'` — Tetris-style: cycle through every variant in a
|
|
1379
|
+
* random shuffle, then reshuffle.
|
|
1380
|
+
*
|
|
1381
|
+
* Each entry in `urls` accepts the same shape as `loadSound`'s second
|
|
1382
|
+
* argument — a URL or codec ladder.
|
|
1383
|
+
*/
|
|
1384
|
+
loadVariants(name: string, urls: readonly (string | readonly string[])[], options?: LoadSoundOptions & VariantsOptions): Promise<Variants>;
|
|
1385
|
+
/** Look up a previously loaded variants bundle. Throws SoundNotFoundError on miss. */
|
|
1386
|
+
variants(name: string): Variants;
|
|
1387
|
+
/** True if `name` was loaded as a variants bundle. */
|
|
1388
|
+
hasVariants(name: string): boolean;
|
|
1238
1389
|
/**
|
|
1239
1390
|
* Bulk-load a batch of sounds with a shared progress reporter. Use this
|
|
1240
1391
|
* to drive a loading screen — the `onProgress` callback fires once per
|
|
@@ -1257,6 +1408,19 @@ interface Engine {
|
|
|
1257
1408
|
}): Sound;
|
|
1258
1409
|
/** Drop a sound from the registry. Active voices keep playing until they end naturally. */
|
|
1259
1410
|
removeSound(name: string): void;
|
|
1411
|
+
/**
|
|
1412
|
+
* Drop a sound from the registry AND evict its decoded buffer from
|
|
1413
|
+
* the internal LRU cache. Use this when hot-swapping themes or
|
|
1414
|
+
* unloading content the user is unlikely to revisit — `removeSound`
|
|
1415
|
+
* alone leaves the buffer hanging in the cache for re-use.
|
|
1416
|
+
*
|
|
1417
|
+
* Active voices keep playing until they end naturally; only future
|
|
1418
|
+
* `play()` calls are affected. Pass `{ evictBuffer: false }` to skip
|
|
1419
|
+
* the cache eviction (equivalent to `removeSound`).
|
|
1420
|
+
*/
|
|
1421
|
+
unloadSound(name: string, options?: {
|
|
1422
|
+
evictBuffer?: boolean;
|
|
1423
|
+
}): void;
|
|
1260
1424
|
hasSound(name: string): boolean;
|
|
1261
1425
|
/**
|
|
1262
1426
|
* Load a single buffer with a region map; spawn region-bound voices via
|
|
@@ -1293,7 +1457,7 @@ interface Engine {
|
|
|
1293
1457
|
stream(name: string): StreamSound;
|
|
1294
1458
|
hasStream(name: string): boolean;
|
|
1295
1459
|
sound(name: string): Sound;
|
|
1296
|
-
bus(name:
|
|
1460
|
+
bus(name: TBusName): Bus;
|
|
1297
1461
|
/**
|
|
1298
1462
|
* Define (with `members`) or look up (without) a `BusGroup` — a logical
|
|
1299
1463
|
* handle that addresses several buses at once. Setting `group.level` or
|
|
@@ -1343,8 +1507,13 @@ interface CrossfadeOptions {
|
|
|
1343
1507
|
/**
|
|
1344
1508
|
* Construct a new engine. Does NOT touch the AudioContext — that happens on
|
|
1345
1509
|
* the first unlock() or play() call. Safe to call before any user gesture.
|
|
1510
|
+
*
|
|
1511
|
+
* The bus-name union is inferred from the `buses` literal you pass in, so
|
|
1512
|
+
* `engine.bus('typo')` becomes a compile-time error when the bus doesn't
|
|
1513
|
+
* exist. If you pass an `EngineConfig` typed as `string`, `engine.bus()`
|
|
1514
|
+
* falls back to accepting any string.
|
|
1346
1515
|
*/
|
|
1347
|
-
declare function createEngine(config?: EngineConfig): Engine
|
|
1516
|
+
declare function createEngine<TBusName extends string = string>(config?: EngineConfig<TBusName>): Engine<TBusName>;
|
|
1348
1517
|
|
|
1349
1518
|
/**
|
|
1350
1519
|
* The Master stage. Headroom-aware gain into an optional brick-wall limiter,
|
|
@@ -1439,4 +1608,4 @@ type NormalizeFlag = boolean | LoudnessOptions;
|
|
|
1439
1608
|
declare function applyLoudnessNormalization(buffer: AudioBuffer, flag: NormalizeFlag): AudioBuffer;
|
|
1440
1609
|
declare function computeNormalizationGain(buffer: AudioBuffer, opts: Required<LoudnessOptions>): number;
|
|
1441
1610
|
|
|
1442
|
-
export { AggregateDecodeError, type ApplyOptions, type AssetResolver, type AudioLevel, type AudioMimeType, Bus, type BusConfig, BusGroup, BusNotFoundError, Compressor, type CompressorConfig, type ConcurrencyConfig, type CrossfadeOptions, type DecodeAttempt, DecodeError, Ducker, type DuckerConfig, type Engine, EngineClosedError, type EngineConfig, type EngineState, type FadeCurve, type FadeOptions, Filter, type FilterConfig, type FilterKind, type FxInsert, type LoadSoundOptions, type LoudnessOptions, Master, type MasterConfig, type MasterLimiterConfig, Music, type MusicLoadOptions, type MusicParts, type MusicPlayOptions, type MusicState, MusicVoice, type NormalizeFlag, Parameter, type ParameterCurve, type PlayOptions, PreloadError, type PreloadFailure, type PreloadItem, type PreloadOptions, type PreloadProgressEvent, type ResolveAssetContext, type ResolvedAsset, Reverb, type ReverbConfig, Send, type SendOptions, type SidechainConfig, type SkipToOutroOptions, Snapshot, type SnapshotState, Sound, SoundNotFoundError, type SpatialOptions, Spatializer, Sprite, type SpriteMap, type SpriteRegion, type SpriteRegionPlayOptions, type StopOptions, StreamSound, StretchProcessor, type StretchWorkletNode, type StretchWorkletOptions, type TickSource, Voice, type VoiceDefaults, type VoiceJitter, ZvukError, applyLoudnessNormalization, canPlay, computeNormalizationGain, createEngine, createStretchWorkletNode, ensureStretchWorklet, mimeForUrl, pickSource, pickSourceOrder };
|
|
1611
|
+
export { AggregateDecodeError, type ApplyOptions, type AssetResolver, type AudioLevel, type AudioMimeType, Bus, type BusConfig, BusGroup, BusNotFoundError, Compressor, type CompressorConfig, type ConcurrencyConfig, type CrossfadeOptions, type DecodeAttempt, DecodeError, type DistanceModel, Ducker, type DuckerConfig, type Engine, EngineClosedError, type EngineConfig, type EngineState, type FadeCurve, type FadeOptions, Filter, type FilterConfig, type FilterKind, type FxInsert, type LoadSoundOptions, type LoudnessOptions, Master, type MasterConfig, type MasterLimiterConfig, Music, type MusicLoadOptions, type MusicParts, type MusicPlayOptions, type MusicState, MusicVoice, type NormalizeFlag, Parameter, type ParameterCurve, type PlayOptions, PreloadError, type PreloadFailure, type PreloadItem, type PreloadOptions, type PreloadProgressEvent, type ResolveAssetContext, type ResolvedAsset, Reverb, type ReverbConfig, Send, type SendOptions, type SidechainConfig, type SkipToOutroOptions, Snapshot, type SnapshotState, Sound, SoundNotFoundError, type SpatialOptions, Spatializer, Sprite, type SpriteMap, type SpriteRegion, type SpriteRegionPlayOptions, type StopOptions, StreamSound, StretchProcessor, type StretchWorkletNode, type StretchWorkletOptions, type TickSource, type VariantStrategy, Variants, type VariantsOptions, Voice, type VoiceDefaults, type VoiceJitter, ZvukError, applyLoudnessNormalization, canPlay, computeNormalizationGain, createEngine, createStretchWorkletNode, ensureStretchWorklet, mimeForUrl, pickSource, pickSourceOrder };
|
package/dist/index.js
CHANGED
|
@@ -1103,7 +1103,9 @@ var AudioContextHost = class {
|
|
|
1103
1103
|
touch() {
|
|
1104
1104
|
if (this._state === "closed") throw new EngineClosedError();
|
|
1105
1105
|
if (!this._ctx) {
|
|
1106
|
-
|
|
1106
|
+
const opts = {};
|
|
1107
|
+
if (this.opts.latencyHint != null) opts.latencyHint = this.opts.latencyHint;
|
|
1108
|
+
this._ctx = new AudioContext(opts);
|
|
1107
1109
|
this.attachVisibilityHandler();
|
|
1108
1110
|
this.attachStateChangeHandler(this._ctx);
|
|
1109
1111
|
}
|
|
@@ -1874,8 +1876,14 @@ var Voice = class _Voice {
|
|
|
1874
1876
|
this.loopEnd = options.loopEnd;
|
|
1875
1877
|
this.stopFade = Math.max(0, deps.defaultStopFade ?? DEFAULT_STOP_FADE_SEC2);
|
|
1876
1878
|
this.gain = ctx.createGain();
|
|
1877
|
-
const initialVolume = resolveJittered(options.volume ?? 1);
|
|
1878
|
-
|
|
1879
|
+
const initialVolume = clamp013(resolveJittered(options.volume ?? 1));
|
|
1880
|
+
const fadeIn = Math.max(0, options.fadeIn ?? 0);
|
|
1881
|
+
if (fadeIn > 0) {
|
|
1882
|
+
this.gain.gain.setValueAtTime(0, ctx.currentTime);
|
|
1883
|
+
this.gain.gain.linearRampToValueAtTime(initialVolume, ctx.currentTime + fadeIn);
|
|
1884
|
+
} else {
|
|
1885
|
+
this.gain.gain.value = initialVolume;
|
|
1886
|
+
}
|
|
1879
1887
|
this.gain.connect(destination);
|
|
1880
1888
|
this.startCtxTime = ctx.currentTime;
|
|
1881
1889
|
this.ended = new Promise((resolve) => {
|
|
@@ -2470,51 +2478,169 @@ function clamp014(v) {
|
|
|
2470
2478
|
return Math.min(1, Math.max(0, v));
|
|
2471
2479
|
}
|
|
2472
2480
|
|
|
2481
|
+
// src/sources/variants.ts
|
|
2482
|
+
var Variants = class {
|
|
2483
|
+
name;
|
|
2484
|
+
count;
|
|
2485
|
+
sounds;
|
|
2486
|
+
strategy;
|
|
2487
|
+
lastIndex = -1;
|
|
2488
|
+
bag = [];
|
|
2489
|
+
constructor(name, sounds, options = {}) {
|
|
2490
|
+
if (sounds.length === 0) throw new Error(`Variants "${name}" requires at least one sound`);
|
|
2491
|
+
this.name = name;
|
|
2492
|
+
this.sounds = sounds;
|
|
2493
|
+
this.count = sounds.length;
|
|
2494
|
+
this.strategy = options.strategy ?? "no-repeat";
|
|
2495
|
+
}
|
|
2496
|
+
/** Spawn a Voice on a randomly-picked variant. */
|
|
2497
|
+
play(options = {}) {
|
|
2498
|
+
return this.sounds[this.pick()].play(options);
|
|
2499
|
+
}
|
|
2500
|
+
/** Force the next pick to use a specific variant index. Useful for tests. */
|
|
2501
|
+
playIndex(index, options = {}) {
|
|
2502
|
+
const i = (index % this.count + this.count) % this.count;
|
|
2503
|
+
this.lastIndex = i;
|
|
2504
|
+
return this.sounds[i].play(options);
|
|
2505
|
+
}
|
|
2506
|
+
pick() {
|
|
2507
|
+
const n = this.count;
|
|
2508
|
+
if (n === 1) return 0;
|
|
2509
|
+
if (this.strategy === "random") {
|
|
2510
|
+
const i2 = Math.floor(Math.random() * n);
|
|
2511
|
+
this.lastIndex = i2;
|
|
2512
|
+
return i2;
|
|
2513
|
+
}
|
|
2514
|
+
if (this.strategy === "shuffle-bag") {
|
|
2515
|
+
if (this.bag.length === 0) {
|
|
2516
|
+
this.bag = Array.from({ length: n }, (_, i3) => i3);
|
|
2517
|
+
for (let i3 = n - 1; i3 > 0; i3--) {
|
|
2518
|
+
const j = Math.floor(Math.random() * (i3 + 1));
|
|
2519
|
+
[this.bag[i3], this.bag[j]] = [this.bag[j], this.bag[i3]];
|
|
2520
|
+
}
|
|
2521
|
+
if (n > 1 && this.bag[0] === this.lastIndex) {
|
|
2522
|
+
[this.bag[0], this.bag[1]] = [this.bag[1], this.bag[0]];
|
|
2523
|
+
}
|
|
2524
|
+
}
|
|
2525
|
+
const i2 = this.bag.shift();
|
|
2526
|
+
this.lastIndex = i2;
|
|
2527
|
+
return i2;
|
|
2528
|
+
}
|
|
2529
|
+
let i = Math.floor(Math.random() * (n - 1));
|
|
2530
|
+
if (i >= this.lastIndex) i++;
|
|
2531
|
+
this.lastIndex = i;
|
|
2532
|
+
return i;
|
|
2533
|
+
}
|
|
2534
|
+
};
|
|
2535
|
+
|
|
2473
2536
|
// src/spatial/spatializer.ts
|
|
2537
|
+
var DEFAULT_REF_DISTANCE = 1;
|
|
2538
|
+
var DEFAULT_MAX_DISTANCE = 1e4;
|
|
2539
|
+
var DEFAULT_ROLLOFF = 1;
|
|
2540
|
+
var DEFAULT_DISTANCE_MODEL = "inverse";
|
|
2541
|
+
var OCCLUSION_OPEN_HZ = 22050;
|
|
2542
|
+
var OCCLUSION_MUFFLED_HZ = 500;
|
|
2474
2543
|
var Spatializer = class {
|
|
2475
|
-
|
|
2544
|
+
ctx;
|
|
2476
2545
|
kind;
|
|
2546
|
+
input;
|
|
2547
|
+
// what the Voice connects into
|
|
2548
|
+
output;
|
|
2549
|
+
// what we connect to the Bus
|
|
2550
|
+
// 2D-only.
|
|
2551
|
+
stereoPan = null;
|
|
2552
|
+
// 3D-only.
|
|
2553
|
+
panner = null;
|
|
2554
|
+
occlusionFilter = null;
|
|
2555
|
+
occlusionGain = null;
|
|
2477
2556
|
constructor(ctx, opts) {
|
|
2557
|
+
this.ctx = ctx;
|
|
2478
2558
|
if (opts.position) {
|
|
2479
2559
|
const panner = ctx.createPanner();
|
|
2480
2560
|
panner.panningModel = "HRTF";
|
|
2481
|
-
panner.distanceModel =
|
|
2482
|
-
panner.refDistance =
|
|
2483
|
-
panner.maxDistance =
|
|
2484
|
-
panner.rolloffFactor =
|
|
2561
|
+
panner.distanceModel = opts.distanceModel ?? DEFAULT_DISTANCE_MODEL;
|
|
2562
|
+
panner.refDistance = opts.refDistance ?? DEFAULT_REF_DISTANCE;
|
|
2563
|
+
panner.maxDistance = opts.maxDistance ?? DEFAULT_MAX_DISTANCE;
|
|
2564
|
+
panner.rolloffFactor = opts.rolloffFactor ?? DEFAULT_ROLLOFF;
|
|
2485
2565
|
const [x, y, z] = opts.position;
|
|
2486
2566
|
this.setPanner3D(panner, x, y, z);
|
|
2487
|
-
|
|
2567
|
+
const filter = ctx.createBiquadFilter();
|
|
2568
|
+
filter.type = "lowpass";
|
|
2569
|
+
filter.frequency.value = OCCLUSION_OPEN_HZ;
|
|
2570
|
+
filter.Q.value = 0.707;
|
|
2571
|
+
const gain = ctx.createGain();
|
|
2572
|
+
gain.gain.value = 1;
|
|
2573
|
+
panner.connect(filter).connect(gain);
|
|
2574
|
+
this.panner = panner;
|
|
2575
|
+
this.occlusionFilter = filter;
|
|
2576
|
+
this.occlusionGain = gain;
|
|
2577
|
+
this.input = panner;
|
|
2578
|
+
this.output = gain;
|
|
2488
2579
|
this.kind = "3d";
|
|
2580
|
+
if (opts.occlusion != null) this.setOcclusion(opts.occlusion);
|
|
2489
2581
|
} else {
|
|
2490
2582
|
const sp = ctx.createStereoPanner();
|
|
2491
2583
|
sp.pan.value = clampPan(opts.pan ?? 0);
|
|
2492
|
-
this.
|
|
2584
|
+
this.stereoPan = sp;
|
|
2585
|
+
this.input = sp;
|
|
2586
|
+
this.output = sp;
|
|
2493
2587
|
this.kind = "2d";
|
|
2494
2588
|
}
|
|
2495
2589
|
}
|
|
2496
2590
|
setPan(pan) {
|
|
2497
|
-
if (this.kind !== "2d") return;
|
|
2498
|
-
this.
|
|
2591
|
+
if (this.kind !== "2d" || !this.stereoPan) return;
|
|
2592
|
+
this.stereoPan.pan.value = clampPan(pan);
|
|
2499
2593
|
}
|
|
2500
2594
|
setPosition(x, y, z) {
|
|
2501
|
-
if (this.kind !== "3d") return;
|
|
2502
|
-
this.setPanner3D(this.
|
|
2595
|
+
if (this.kind !== "3d" || !this.panner) return;
|
|
2596
|
+
this.setPanner3D(this.panner, x, y, z);
|
|
2597
|
+
}
|
|
2598
|
+
setRefDistance(d) {
|
|
2599
|
+
if (!this.panner) return;
|
|
2600
|
+
this.panner.refDistance = Math.max(0, d);
|
|
2601
|
+
}
|
|
2602
|
+
setMaxDistance(d) {
|
|
2603
|
+
if (!this.panner) return;
|
|
2604
|
+
this.panner.maxDistance = Math.max(0, d);
|
|
2503
2605
|
}
|
|
2504
|
-
|
|
2606
|
+
setRolloffFactor(f) {
|
|
2607
|
+
if (!this.panner) return;
|
|
2608
|
+
this.panner.rolloffFactor = Math.max(0, f);
|
|
2609
|
+
}
|
|
2610
|
+
setDistanceModel(m) {
|
|
2611
|
+
if (!this.panner) return;
|
|
2612
|
+
this.panner.distanceModel = m;
|
|
2613
|
+
}
|
|
2614
|
+
/**
|
|
2615
|
+
* Set occlusion amount (0..1). Drives the internal lowpass cutoff
|
|
2616
|
+
* and a small gain dip — independent of distance attenuation.
|
|
2617
|
+
* No-op on 2D spatializers.
|
|
2618
|
+
*/
|
|
2619
|
+
setOcclusion(amount) {
|
|
2620
|
+
if (!this.occlusionFilter || !this.occlusionGain) return;
|
|
2621
|
+
const a = clamp015(amount);
|
|
2622
|
+
const cutoff = OCCLUSION_OPEN_HZ * (OCCLUSION_MUFFLED_HZ / OCCLUSION_OPEN_HZ) ** a;
|
|
2623
|
+
const now = this.ctx.currentTime;
|
|
2624
|
+
this.occlusionFilter.frequency.setValueAtTime(cutoff, now);
|
|
2625
|
+
const gainLin = 10 ** (-6 * a / 20);
|
|
2626
|
+
this.occlusionGain.gain.setValueAtTime(gainLin, now);
|
|
2627
|
+
}
|
|
2628
|
+
/** Connects the spatializer's output into `dest` and returns the input the Voice should use. */
|
|
2505
2629
|
connectInto(dest) {
|
|
2506
|
-
this.
|
|
2507
|
-
return this.
|
|
2630
|
+
this.output.connect(dest);
|
|
2631
|
+
return this.input;
|
|
2508
2632
|
}
|
|
2509
2633
|
dispose() {
|
|
2510
2634
|
try {
|
|
2511
|
-
this.
|
|
2635
|
+
this.input.disconnect();
|
|
2636
|
+
this.occlusionFilter?.disconnect();
|
|
2637
|
+
this.occlusionGain?.disconnect();
|
|
2512
2638
|
} catch {
|
|
2513
2639
|
}
|
|
2514
2640
|
}
|
|
2515
2641
|
setPanner3D(p, x, y, z) {
|
|
2516
2642
|
if (typeof p.positionX?.setValueAtTime === "function") {
|
|
2517
|
-
const now =
|
|
2643
|
+
const now = this.ctx.currentTime;
|
|
2518
2644
|
p.positionX.setValueAtTime(x, now);
|
|
2519
2645
|
p.positionY.setValueAtTime(y, now);
|
|
2520
2646
|
p.positionZ.setValueAtTime(z, now);
|
|
@@ -2527,6 +2653,10 @@ var Spatializer = class {
|
|
|
2527
2653
|
function clampPan(v) {
|
|
2528
2654
|
return Math.max(-1, Math.min(1, v));
|
|
2529
2655
|
}
|
|
2656
|
+
function clamp015(v) {
|
|
2657
|
+
if (Number.isNaN(v)) return 0;
|
|
2658
|
+
return Math.max(0, Math.min(1, v));
|
|
2659
|
+
}
|
|
2530
2660
|
|
|
2531
2661
|
// src/mixer/master.ts
|
|
2532
2662
|
var Master = class {
|
|
@@ -2675,14 +2805,24 @@ var EngineImpl = class {
|
|
|
2675
2805
|
sprites = /* @__PURE__ */ new Map();
|
|
2676
2806
|
streams = /* @__PURE__ */ new Map();
|
|
2677
2807
|
musics = /* @__PURE__ */ new Map();
|
|
2808
|
+
variantsByName = /* @__PURE__ */ new Map();
|
|
2678
2809
|
busGroups = /* @__PURE__ */ new Map();
|
|
2679
2810
|
soloedBuses = /* @__PURE__ */ new Set();
|
|
2811
|
+
/**
|
|
2812
|
+
* URL fingerprint per loadSound call so `unloadSound` can evict the
|
|
2813
|
+
* matching entries from the Decoder LRU. Sounds registered via
|
|
2814
|
+
* `createSound` (procedural buffers) leave no fingerprint here.
|
|
2815
|
+
*/
|
|
2816
|
+
soundUrls = /* @__PURE__ */ new Map();
|
|
2680
2817
|
voices = /* @__PURE__ */ new Map();
|
|
2681
2818
|
parameters = /* @__PURE__ */ new Map();
|
|
2682
2819
|
config;
|
|
2683
2820
|
constructor(config) {
|
|
2684
2821
|
this.config = config;
|
|
2685
|
-
this.host = new AudioContextHost({
|
|
2822
|
+
this.host = new AudioContextHost({
|
|
2823
|
+
autoPauseOnHidden: config.autoPauseOnHidden,
|
|
2824
|
+
latencyHint: config.latencyHint
|
|
2825
|
+
});
|
|
2686
2826
|
this.decoder = new Decoder(() => this.host.touch());
|
|
2687
2827
|
const declared = Object.keys(config.buses ?? {});
|
|
2688
2828
|
this.busOrder = declared.length > 0 ? declared : ["default"];
|
|
@@ -2719,6 +2859,8 @@ var EngineImpl = class {
|
|
|
2719
2859
|
this.sounds.clear();
|
|
2720
2860
|
this.sprites.clear();
|
|
2721
2861
|
this.musics.clear();
|
|
2862
|
+
this.variantsByName.clear();
|
|
2863
|
+
this.soundUrls.clear();
|
|
2722
2864
|
for (const s of this.streams.values()) s.dispose();
|
|
2723
2865
|
this.streams.clear();
|
|
2724
2866
|
this.parameters.clear();
|
|
@@ -2734,6 +2876,7 @@ var EngineImpl = class {
|
|
|
2734
2876
|
if (options.normalize) {
|
|
2735
2877
|
buffer = applyLoudnessNormalization(buffer, options.normalize);
|
|
2736
2878
|
}
|
|
2879
|
+
this.soundUrls.set(name, typeof url === "string" ? [url] : [...url]);
|
|
2737
2880
|
return this.createSound(name, buffer, { bus: options.bus });
|
|
2738
2881
|
}
|
|
2739
2882
|
async resolveBuffer(name, url, decodeOpts) {
|
|
@@ -2808,6 +2951,27 @@ var EngineImpl = class {
|
|
|
2808
2951
|
hasSprite(name) {
|
|
2809
2952
|
return this.sprites.has(name);
|
|
2810
2953
|
}
|
|
2954
|
+
async loadVariants(name, urls, options = {}) {
|
|
2955
|
+
if (urls.length === 0) {
|
|
2956
|
+
throw new Error(`engine.loadVariants("${name}") requires at least one URL set`);
|
|
2957
|
+
}
|
|
2958
|
+
const { strategy, ...loadOpts } = options;
|
|
2959
|
+
const sounds = [];
|
|
2960
|
+
for (let i = 0; i < urls.length; i++) {
|
|
2961
|
+
sounds.push(await this.loadSound(`__variant:${name}:${i}`, urls[i], loadOpts));
|
|
2962
|
+
}
|
|
2963
|
+
const v = new Variants(name, sounds, { strategy });
|
|
2964
|
+
this.variantsByName.set(name, v);
|
|
2965
|
+
return v;
|
|
2966
|
+
}
|
|
2967
|
+
variants(name) {
|
|
2968
|
+
const v = this.variantsByName.get(name);
|
|
2969
|
+
if (!v) throw new SoundNotFoundError(suggest(name, [...this.variantsByName.keys()]));
|
|
2970
|
+
return v;
|
|
2971
|
+
}
|
|
2972
|
+
hasVariants(name) {
|
|
2973
|
+
return this.variantsByName.has(name);
|
|
2974
|
+
}
|
|
2811
2975
|
async loadMusic(name, parts, options = {}) {
|
|
2812
2976
|
if (this.host.state === "closed") throw new EngineClosedError();
|
|
2813
2977
|
this.host.touch();
|
|
@@ -2931,6 +3095,16 @@ var EngineImpl = class {
|
|
|
2931
3095
|
removeSound(name) {
|
|
2932
3096
|
this.sounds.delete(name);
|
|
2933
3097
|
}
|
|
3098
|
+
unloadSound(name, options = {}) {
|
|
3099
|
+
this.sounds.delete(name);
|
|
3100
|
+
if (options.evictBuffer ?? true) {
|
|
3101
|
+
const urls = this.soundUrls.get(name);
|
|
3102
|
+
if (urls) {
|
|
3103
|
+
for (const u of urls) this.decoder.evict(u);
|
|
3104
|
+
}
|
|
3105
|
+
}
|
|
3106
|
+
this.soundUrls.delete(name);
|
|
3107
|
+
}
|
|
2934
3108
|
hasSound(name) {
|
|
2935
3109
|
return this.sounds.has(name);
|
|
2936
3110
|
}
|
|
@@ -3082,6 +3256,6 @@ function levenshtein(a, b) {
|
|
|
3082
3256
|
return prev[b.length];
|
|
3083
3257
|
}
|
|
3084
3258
|
|
|
3085
|
-
export { AggregateDecodeError, Bus, BusGroup, BusNotFoundError, Compressor, DecodeError, Ducker, EngineClosedError, Filter, Master, Music, MusicVoice, Parameter, PreloadError, Reverb, Send, Snapshot, Sound, SoundNotFoundError, Spatializer, Sprite, StreamSound, StretchProcessor, Voice, ZvukError, applyLoudnessNormalization, canPlay, computeNormalizationGain, createEngine, createStretchWorkletNode, ensureStretchWorklet, mimeForUrl, pickSource, pickSourceOrder };
|
|
3259
|
+
export { AggregateDecodeError, Bus, BusGroup, BusNotFoundError, Compressor, DecodeError, Ducker, EngineClosedError, Filter, Master, Music, MusicVoice, Parameter, PreloadError, Reverb, Send, Snapshot, Sound, SoundNotFoundError, Spatializer, Sprite, StreamSound, StretchProcessor, Variants, Voice, ZvukError, applyLoudnessNormalization, canPlay, computeNormalizationGain, createEngine, createStretchWorkletNode, ensureStretchWorklet, mimeForUrl, pickSource, pickSourceOrder };
|
|
3086
3260
|
//# sourceMappingURL=index.js.map
|
|
3087
3261
|
//# sourceMappingURL=index.js.map
|