@schmooky/zvuk 1.10.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 CHANGED
@@ -238,10 +238,27 @@ interface VoiceDefaults {
238
238
  */
239
239
  stopFade?: number;
240
240
  }
241
- interface EngineConfig {
242
- buses?: Record<string, BusConfig>;
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` —
@@ -343,6 +360,13 @@ interface SpatialOptions {
343
360
  interface PlayOptions {
344
361
  /** Initial volume (0..1). Default 1. */
345
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;
346
370
  /** Playback rate. 1 = source speed. Random jitter optional. */
347
371
  pitch?: number | VoiceJitter;
348
372
  /** Loop the voice. Default false. */
@@ -1242,6 +1266,45 @@ declare class StreamSound {
1242
1266
  dispose(): void;
1243
1267
  }
1244
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
+
1245
1308
  interface SnapshotState {
1246
1309
  buses: Record<string, {
1247
1310
  level: number;
@@ -1271,7 +1334,13 @@ declare class Snapshot {
1271
1334
  apply(opts?: ApplyOptions): Promise<void>;
1272
1335
  }
1273
1336
 
1274
- interface Engine {
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> {
1275
1344
  readonly state: EngineState;
1276
1345
  readonly now: number;
1277
1346
  /** Live AudioContext. Constructs one on first read. Throws if engine is closed. */
@@ -1297,6 +1366,26 @@ interface Engine {
1297
1366
  * `string` URL, or `undefined`/`null` to fall through to the URL list.
1298
1367
  */
1299
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;
1300
1389
  /**
1301
1390
  * Bulk-load a batch of sounds with a shared progress reporter. Use this
1302
1391
  * to drive a loading screen — the `onProgress` callback fires once per
@@ -1319,6 +1408,19 @@ interface Engine {
1319
1408
  }): Sound;
1320
1409
  /** Drop a sound from the registry. Active voices keep playing until they end naturally. */
1321
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;
1322
1424
  hasSound(name: string): boolean;
1323
1425
  /**
1324
1426
  * Load a single buffer with a region map; spawn region-bound voices via
@@ -1355,7 +1457,7 @@ interface Engine {
1355
1457
  stream(name: string): StreamSound;
1356
1458
  hasStream(name: string): boolean;
1357
1459
  sound(name: string): Sound;
1358
- bus(name: string): Bus;
1460
+ bus(name: TBusName): Bus;
1359
1461
  /**
1360
1462
  * Define (with `members`) or look up (without) a `BusGroup` — a logical
1361
1463
  * handle that addresses several buses at once. Setting `group.level` or
@@ -1405,8 +1507,13 @@ interface CrossfadeOptions {
1405
1507
  /**
1406
1508
  * Construct a new engine. Does NOT touch the AudioContext — that happens on
1407
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.
1408
1515
  */
1409
- declare function createEngine(config?: EngineConfig): Engine;
1516
+ declare function createEngine<TBusName extends string = string>(config?: EngineConfig<TBusName>): Engine<TBusName>;
1410
1517
 
1411
1518
  /**
1412
1519
  * The Master stage. Headroom-aware gain into an optional brick-wall limiter,
@@ -1501,4 +1608,4 @@ type NormalizeFlag = boolean | LoudnessOptions;
1501
1608
  declare function applyLoudnessNormalization(buffer: AudioBuffer, flag: NormalizeFlag): AudioBuffer;
1502
1609
  declare function computeNormalizationGain(buffer: AudioBuffer, opts: Required<LoudnessOptions>): number;
1503
1610
 
1504
- 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, 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
- this._ctx = new AudioContext();
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
- this.gain.gain.value = clamp013(initialVolume);
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,6 +2478,61 @@ 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
2474
2537
  var DEFAULT_REF_DISTANCE = 1;
2475
2538
  var DEFAULT_MAX_DISTANCE = 1e4;
@@ -2742,14 +2805,24 @@ var EngineImpl = class {
2742
2805
  sprites = /* @__PURE__ */ new Map();
2743
2806
  streams = /* @__PURE__ */ new Map();
2744
2807
  musics = /* @__PURE__ */ new Map();
2808
+ variantsByName = /* @__PURE__ */ new Map();
2745
2809
  busGroups = /* @__PURE__ */ new Map();
2746
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();
2747
2817
  voices = /* @__PURE__ */ new Map();
2748
2818
  parameters = /* @__PURE__ */ new Map();
2749
2819
  config;
2750
2820
  constructor(config) {
2751
2821
  this.config = config;
2752
- this.host = new AudioContextHost({ autoPauseOnHidden: config.autoPauseOnHidden });
2822
+ this.host = new AudioContextHost({
2823
+ autoPauseOnHidden: config.autoPauseOnHidden,
2824
+ latencyHint: config.latencyHint
2825
+ });
2753
2826
  this.decoder = new Decoder(() => this.host.touch());
2754
2827
  const declared = Object.keys(config.buses ?? {});
2755
2828
  this.busOrder = declared.length > 0 ? declared : ["default"];
@@ -2786,6 +2859,8 @@ var EngineImpl = class {
2786
2859
  this.sounds.clear();
2787
2860
  this.sprites.clear();
2788
2861
  this.musics.clear();
2862
+ this.variantsByName.clear();
2863
+ this.soundUrls.clear();
2789
2864
  for (const s of this.streams.values()) s.dispose();
2790
2865
  this.streams.clear();
2791
2866
  this.parameters.clear();
@@ -2801,6 +2876,7 @@ var EngineImpl = class {
2801
2876
  if (options.normalize) {
2802
2877
  buffer = applyLoudnessNormalization(buffer, options.normalize);
2803
2878
  }
2879
+ this.soundUrls.set(name, typeof url === "string" ? [url] : [...url]);
2804
2880
  return this.createSound(name, buffer, { bus: options.bus });
2805
2881
  }
2806
2882
  async resolveBuffer(name, url, decodeOpts) {
@@ -2875,6 +2951,27 @@ var EngineImpl = class {
2875
2951
  hasSprite(name) {
2876
2952
  return this.sprites.has(name);
2877
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
+ }
2878
2975
  async loadMusic(name, parts, options = {}) {
2879
2976
  if (this.host.state === "closed") throw new EngineClosedError();
2880
2977
  this.host.touch();
@@ -2998,6 +3095,16 @@ var EngineImpl = class {
2998
3095
  removeSound(name) {
2999
3096
  this.sounds.delete(name);
3000
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
+ }
3001
3108
  hasSound(name) {
3002
3109
  return this.sounds.has(name);
3003
3110
  }
@@ -3149,6 +3256,6 @@ function levenshtein(a, b) {
3149
3256
  return prev[b.length];
3150
3257
  }
3151
3258
 
3152
- 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 };
3153
3260
  //# sourceMappingURL=index.js.map
3154
3261
  //# sourceMappingURL=index.js.map