@schmooky/zvuk 1.4.0 → 1.6.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
@@ -17,6 +17,20 @@ interface DecodeAttempt {
17
17
  readonly url: string;
18
18
  readonly cause: unknown;
19
19
  }
20
+ interface PreloadFailure {
21
+ readonly name: string;
22
+ readonly cause: unknown;
23
+ }
24
+ /**
25
+ * Thrown by `engine.preload(...)` when one or more items in the batch fail.
26
+ * Other items in the batch still complete; this only fires after every item
27
+ * has settled, so a single broken asset doesn't short-circuit the rest of a
28
+ * loading screen.
29
+ */
30
+ declare class PreloadError extends ZvukError {
31
+ readonly failures: readonly PreloadFailure[];
32
+ constructor(failures: readonly PreloadFailure[]);
33
+ }
20
34
  /**
21
35
  * Thrown when every URL in a fallback list fails to load. Subclass of
22
36
  * DecodeError so existing `catch (e instanceof DecodeError)` paths still
@@ -283,6 +297,21 @@ interface PlayOptions {
283
297
  loopStart?: number;
284
298
  /** When loop=true, end of the loop region (seconds). */
285
299
  loopEnd?: number;
300
+ /**
301
+ * Equal-power crossfade duration (seconds) at the loop boundary. When
302
+ * `loop` is true and this is non-zero, zvuk spawns a parallel buffer
303
+ * source at every loop point and ramps between them — masking the click
304
+ * that AudioBufferSourceNode's native loop produces when the region
305
+ * doesn't end on a zero crossing.
306
+ *
307
+ * Default `0` (off — native hard-cut loop). Cost is one extra
308
+ * AudioBufferSourceNode + GainNode per loop iteration; with default
309
+ * Web Audio dispatch this is well under 1% CPU per voice.
310
+ *
311
+ * Ignored if `loop` is false, or if the loop region is shorter than
312
+ * twice the crossfade window (silent fallback to native loop).
313
+ */
314
+ loopCrossfade?: number;
286
315
  }
287
316
  interface LoudnessOptions$1 {
288
317
  /** Target RMS (linear, 0..1). Default 0.1 (~ -20 dBFS). */
@@ -302,6 +331,50 @@ interface LoadSoundOptions {
302
331
  */
303
332
  normalize?: boolean | LoudnessOptions$1;
304
333
  }
334
+ /**
335
+ * One entry in a `engine.preload(...)` batch. Mirrors `engine.loadSound`'s
336
+ * signature so callers can hand the same data to either path.
337
+ */
338
+ interface PreloadItem {
339
+ /** Sound name, registered on `engine.sound(name)` after preload completes. */
340
+ name: string;
341
+ /** URL or codec ladder — same shape as `engine.loadSound`. */
342
+ url: string | readonly string[];
343
+ /** Per-item options (bus, normalize, etc.). Forwarded to `loadSound`. */
344
+ options?: LoadSoundOptions;
345
+ }
346
+ interface PreloadProgressEvent {
347
+ /** Name of the item that just completed (success or failure). */
348
+ readonly name: string;
349
+ /** Outcome — `'loaded'` on decode success, `'failed'` otherwise. */
350
+ readonly status: 'loaded' | 'failed';
351
+ /** Error attached when `status === 'failed'`. */
352
+ readonly error?: unknown;
353
+ /** Items settled so far (loaded + failed). */
354
+ readonly completed: number;
355
+ /** Total items in the batch. */
356
+ readonly total: number;
357
+ }
358
+ interface PreloadOptions {
359
+ /**
360
+ * Cancels the whole preload. In-flight fetches receive the abort; pending
361
+ * items aren't started. The promise rejects with the signal's abort reason.
362
+ */
363
+ signal?: AbortSignal;
364
+ /**
365
+ * Maximum concurrent loads. Default 4 — chosen for balance with browser
366
+ * connection limits (typically 6 per host) so the rest of the page's
367
+ * fetches don't starve. Lower for cheap mobile data plans, higher when
368
+ * you control the host and want to saturate.
369
+ */
370
+ concurrency?: number;
371
+ /**
372
+ * Fires once per item as it settles. Use this to drive a loading-screen
373
+ * progress bar. The event is cumulative — `event.completed / event.total`
374
+ * is a fraction in [0..1].
375
+ */
376
+ onProgress?: (event: PreloadProgressEvent) => void;
377
+ }
305
378
 
306
379
  /**
307
380
  * PannerNode wrapper. Inserted between a Voice and its Bus when a play call
@@ -370,8 +443,14 @@ declare class Voice {
370
443
  private loopEnd;
371
444
  private regionTimer;
372
445
  private stopFade;
446
+ private crossfadeSec;
447
+ private crossfadeRegionStart;
448
+ private crossfadeRegionLen;
449
+ private crossfadeChain;
450
+ private crossfadeArmTimer;
373
451
  static nextId: number;
374
452
  constructor(deps: VoiceDeps);
453
+ private shouldUseLoopCrossfade;
375
454
  fade(opts: FadeOptions): Promise<void>;
376
455
  /**
377
456
  * Stop the voice. Applies a short linear gain ramp (default ~8 ms) before
@@ -385,6 +464,8 @@ declare class Voice {
385
464
  * actually stops (i.e. after the ramp completes).
386
465
  */
387
466
  stop(opts?: StopOptions): void;
467
+ private activeSources;
468
+ private stopAllSources;
388
469
  /**
389
470
  * Pause this voice. Tracks the playback offset so resume() picks up
390
471
  * where it left off. No-op on a finished voice.
@@ -412,6 +493,21 @@ declare class Voice {
412
493
  private createSourceNode;
413
494
  private armRegionTimer;
414
495
  private bindSourceLifecycle;
496
+ /**
497
+ * Begin the loop-crossfade chain. Spawns the first segment immediately at
498
+ * full level, then arms a setTimeout to spawn the next one shortly before
499
+ * the boundary. Each subsequent spawn re-arms its own follow-up.
500
+ *
501
+ * Audio scheduling uses absolute `ctx.currentTime` values so drift between
502
+ * setTimeout (wall clock) and the audio thread doesn't cause click-y
503
+ * misalignment — setTimeout only needs to wake us in time to call
504
+ * `source.start(when, ...)` before `when`.
505
+ */
506
+ private startCrossfadeChain;
507
+ private spawnCrossfadeSegment;
508
+ private armNextCrossfadeSegment;
509
+ private releaseCrossfadeSegment;
510
+ private get inCrossfadeMode();
415
511
  private computeOffset;
416
512
  }
417
513
 
@@ -832,6 +928,22 @@ interface Engine {
832
928
  * `string` URL, or `undefined`/`null` to fall through to the URL list.
833
929
  */
834
930
  loadSound(name: string, url: string | readonly string[], options?: LoadSoundOptions): Promise<Sound>;
931
+ /**
932
+ * Bulk-load a batch of sounds with a shared progress reporter. Use this
933
+ * to drive a loading screen — the `onProgress` callback fires once per
934
+ * item as it settles, and the returned promise resolves when every item
935
+ * has either succeeded or failed.
936
+ *
937
+ * If any items fail, the promise rejects with `PreloadError` after every
938
+ * item has settled (a single broken asset doesn't short-circuit the rest
939
+ * of the screen). On success the items are registered as if you'd called
940
+ * `engine.loadSound(...)` for each.
941
+ *
942
+ * Concurrency is capped (default 4) so the rest of the page's fetches
943
+ * aren't starved by a 100-asset preload competing for the browser's
944
+ * per-host connection budget.
945
+ */
946
+ preload(items: readonly PreloadItem[], options?: PreloadOptions): Promise<void>;
835
947
  /** Register a Sound from an AudioBuffer you constructed yourself (procedural, custom-decoded, time-stretched). */
836
948
  createSound(name: string, buffer: AudioBuffer, options?: {
837
949
  bus?: string;
@@ -981,4 +1093,4 @@ type NormalizeFlag = boolean | LoudnessOptions;
981
1093
  declare function applyLoudnessNormalization(buffer: AudioBuffer, flag: NormalizeFlag): AudioBuffer;
982
1094
  declare function computeNormalizationGain(buffer: AudioBuffer, opts: Required<LoudnessOptions>): number;
983
1095
 
984
- export { AggregateDecodeError, type ApplyOptions, type AssetResolver, type AudioMimeType, Bus, type BusConfig, 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, type NormalizeFlag, Parameter, type ParameterCurve, type PlayOptions, type ResolveAssetContext, type ResolvedAsset, Reverb, type ReverbConfig, type SidechainConfig, 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 };
1096
+ export { AggregateDecodeError, type ApplyOptions, type AssetResolver, type AudioMimeType, Bus, type BusConfig, 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, type NormalizeFlag, Parameter, type ParameterCurve, type PlayOptions, PreloadError, type PreloadFailure, type PreloadItem, type PreloadOptions, type PreloadProgressEvent, type ResolveAssetContext, type ResolvedAsset, Reverb, type ReverbConfig, type SidechainConfig, 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 };
package/dist/index.js CHANGED
@@ -29,6 +29,16 @@ var DecodeError = class extends ZvukError {
29
29
  this.name = "DecodeError";
30
30
  }
31
31
  };
32
+ var PreloadError = class extends ZvukError {
33
+ failures;
34
+ constructor(failures) {
35
+ const summary = failures.map((f) => ` - ${f.name}: ${f.cause instanceof Error ? f.cause.message : String(f.cause)}`).join("\n");
36
+ super(`Failed to preload ${failures.length} item(s):
37
+ ${summary}`);
38
+ this.name = "PreloadError";
39
+ this.failures = failures;
40
+ }
41
+ };
32
42
  var AggregateDecodeError = class extends DecodeError {
33
43
  attempts;
34
44
  constructor(urls, attempts) {
@@ -1264,6 +1274,15 @@ var Voice = class _Voice {
1264
1274
  loopEnd;
1265
1275
  regionTimer = null;
1266
1276
  stopFade;
1277
+ // Loop-crossfade state. Inactive when crossfadeSec === 0.
1278
+ // In crossfade mode, `source` is the most-recently-armed segment and the
1279
+ // `crossfadeChain` carries every segment currently scheduled or live so
1280
+ // that stop/pause/setPlaybackRate can fan out across them.
1281
+ crossfadeSec = 0;
1282
+ crossfadeRegionStart = 0;
1283
+ crossfadeRegionLen = 0;
1284
+ crossfadeChain = [];
1285
+ crossfadeArmTimer = null;
1267
1286
  static nextId = 1;
1268
1287
  constructor(deps) {
1269
1288
  const { ctx, buffer, destination, options } = deps;
@@ -1287,13 +1306,10 @@ var Voice = class _Voice {
1287
1306
  const initialVolume = resolveJittered(options.volume ?? 1);
1288
1307
  this.gain.gain.value = clamp012(initialVolume);
1289
1308
  this.gain.connect(destination);
1290
- this.source = this.createSourceNode(this.basePitch);
1291
1309
  this.startCtxTime = ctx.currentTime;
1292
1310
  this.ended = new Promise((resolve) => {
1293
1311
  this.resolveEnded = resolve;
1294
1312
  });
1295
- this.bindSourceLifecycle(this.source, () => {
1296
- });
1297
1313
  if (options.signal) {
1298
1314
  if (options.signal.aborted) {
1299
1315
  queueMicrotask(() => this.stop());
@@ -1301,14 +1317,34 @@ var Voice = class _Voice {
1301
1317
  options.signal.addEventListener("abort", () => this.stop(), { once: true });
1302
1318
  }
1303
1319
  }
1304
- try {
1305
- this.source.start(0, this.startOffset);
1306
- } catch {
1320
+ if (this.shouldUseLoopCrossfade(options)) {
1321
+ this.crossfadeSec = options.loopCrossfade;
1322
+ this.crossfadeRegionStart = options.loopStart ?? this.startOffset;
1323
+ const regionEnd = options.loopEnd ?? buffer.duration;
1324
+ this.crossfadeRegionLen = Math.max(0, regionEnd - this.crossfadeRegionStart);
1325
+ this.source = this.startCrossfadeChain(ctx.currentTime);
1326
+ } else {
1327
+ this.source = this.createSourceNode(this.basePitch);
1328
+ this.bindSourceLifecycle(this.source, () => {
1329
+ });
1330
+ try {
1331
+ this.source.start(0, this.startOffset);
1332
+ } catch {
1333
+ }
1334
+ this.armRegionTimer(this.regionDuration);
1307
1335
  }
1308
- this.armRegionTimer(this.regionDuration);
1309
1336
  queueMicrotask(() => this.emit("started"));
1310
1337
  void this.ended.then(() => deps.onEnded(this));
1311
1338
  }
1339
+ shouldUseLoopCrossfade(options) {
1340
+ if (!this.loop) return false;
1341
+ const cf = options.loopCrossfade;
1342
+ if (cf == null || cf <= 0) return false;
1343
+ const start = options.loopStart ?? this.startOffset;
1344
+ const end = options.loopEnd ?? this.buffer.duration;
1345
+ const len = end - start;
1346
+ return len > cf * 2;
1347
+ }
1312
1348
  fade(opts) {
1313
1349
  const param = this.gain.gain;
1314
1350
  const now = this.ctx.currentTime;
@@ -1329,18 +1365,19 @@ var Voice = class _Voice {
1329
1365
  stop(opts = {}) {
1330
1366
  if (this.done || this.stopping) return;
1331
1367
  const fade = Math.max(0, opts.fade ?? this.stopFade);
1368
+ if (this.crossfadeArmTimer != null) {
1369
+ clearTimeout(this.crossfadeArmTimer);
1370
+ this.crossfadeArmTimer = null;
1371
+ }
1332
1372
  if (fade === 0) {
1333
- try {
1334
- this.source.stop();
1335
- } catch {
1336
- }
1373
+ this.stopAllSources(0);
1337
1374
  this.finish("ended");
1338
1375
  return;
1339
1376
  }
1340
1377
  this.stopping = true;
1341
1378
  const now = this.ctx.currentTime;
1342
1379
  const stopAt = now + fade;
1343
- this.source.onended = null;
1380
+ for (const src of this.activeSources()) src.onended = null;
1344
1381
  if (this.regionTimer != null) {
1345
1382
  clearTimeout(this.regionTimer);
1346
1383
  this.regionTimer = null;
@@ -1350,13 +1387,26 @@ var Voice = class _Voice {
1350
1387
  param.cancelScheduledValues(now);
1351
1388
  param.setValueAtTime(param.value, now);
1352
1389
  param.linearRampToValueAtTime(0, stopAt);
1353
- this.source.stop(stopAt);
1390
+ this.stopAllSources(stopAt);
1354
1391
  } catch {
1355
1392
  this.finish("ended");
1356
1393
  return;
1357
1394
  }
1358
1395
  setTimeout(() => this.finish("ended"), fade * 1e3);
1359
1396
  }
1397
+ activeSources() {
1398
+ if (this.inCrossfadeMode) return this.crossfadeChain.map((e) => e.source);
1399
+ return [this.source];
1400
+ }
1401
+ stopAllSources(when) {
1402
+ for (const src of this.activeSources()) {
1403
+ try {
1404
+ if (when === 0) src.stop();
1405
+ else src.stop(when);
1406
+ } catch {
1407
+ }
1408
+ }
1409
+ }
1360
1410
  /**
1361
1411
  * Pause this voice. Tracks the playback offset so resume() picks up
1362
1412
  * where it left off. No-op on a finished voice.
@@ -1371,33 +1421,44 @@ var Voice = class _Voice {
1371
1421
  clearTimeout(this.regionTimer);
1372
1422
  this.regionTimer = null;
1373
1423
  }
1374
- try {
1375
- this.source.onended = null;
1376
- this.source.stop();
1377
- } catch {
1424
+ if (this.crossfadeArmTimer != null) {
1425
+ clearTimeout(this.crossfadeArmTimer);
1426
+ this.crossfadeArmTimer = null;
1378
1427
  }
1379
- try {
1380
- this.source.disconnect();
1381
- } catch {
1428
+ for (const src of this.activeSources()) {
1429
+ try {
1430
+ src.onended = null;
1431
+ src.stop();
1432
+ } catch {
1433
+ }
1434
+ try {
1435
+ src.disconnect();
1436
+ } catch {
1437
+ }
1382
1438
  }
1439
+ if (this.inCrossfadeMode) this.crossfadeChain = [];
1383
1440
  this.emit("paused");
1384
1441
  }
1385
1442
  /** Resume from the offset captured on pause(). No-op when not paused. */
1386
1443
  resume() {
1387
1444
  if (this.done || !this.paused) return;
1388
1445
  this.paused = false;
1389
- this.source = this.createSourceNode(this.basePitch);
1390
- this.bindSourceLifecycle(this.source, () => {
1391
- });
1392
1446
  this.startCtxTime = this.ctx.currentTime;
1393
- try {
1394
- this.source.start(0, this.pausedOffset);
1395
- } catch {
1396
- }
1397
- if (this.regionDuration != null) {
1398
- const consumed = Math.max(0, this.pausedOffset - this.startOffset);
1399
- const remaining = Math.max(0, this.regionDuration - consumed);
1400
- this.armRegionTimer(remaining);
1447
+ if (this.inCrossfadeMode) {
1448
+ this.source = this.startCrossfadeChain(this.startCtxTime);
1449
+ } else {
1450
+ this.source = this.createSourceNode(this.basePitch);
1451
+ this.bindSourceLifecycle(this.source, () => {
1452
+ });
1453
+ try {
1454
+ this.source.start(0, this.pausedOffset);
1455
+ } catch {
1456
+ }
1457
+ if (this.regionDuration != null) {
1458
+ const consumed = Math.max(0, this.pausedOffset - this.startOffset);
1459
+ const remaining = Math.max(0, this.regionDuration - consumed);
1460
+ this.armRegionTimer(remaining);
1461
+ }
1401
1462
  }
1402
1463
  this.emit("resumed");
1403
1464
  }
@@ -1419,12 +1480,14 @@ var Voice = class _Voice {
1419
1480
  }
1420
1481
  this.basePitch = r;
1421
1482
  if (this.paused) return;
1422
- const param = this.source.playbackRate;
1423
- if (duration === 0) {
1424
- param.value = r;
1425
- return;
1483
+ for (const src of this.activeSources()) {
1484
+ const param = src.playbackRate;
1485
+ if (duration === 0) {
1486
+ param.value = r;
1487
+ } else {
1488
+ applyRamp(param, this.ctx.currentTime, r, duration, opts.curve ?? "linear");
1489
+ }
1426
1490
  }
1427
- applyRamp(param, this.ctx.currentTime, r, duration, opts.curve ?? "linear");
1428
1491
  }
1429
1492
  get playbackRate() {
1430
1493
  return this.basePitch;
@@ -1475,11 +1538,17 @@ var Voice = class _Voice {
1475
1538
  clearTimeout(this.regionTimer);
1476
1539
  this.regionTimer = null;
1477
1540
  }
1541
+ if (this.crossfadeArmTimer != null) {
1542
+ clearTimeout(this.crossfadeArmTimer);
1543
+ this.crossfadeArmTimer = null;
1544
+ }
1478
1545
  try {
1479
- this.source.disconnect();
1546
+ for (const src of this.activeSources()) src.disconnect();
1547
+ for (const e of this.crossfadeChain) e.gain.disconnect();
1480
1548
  this.gain.disconnect();
1481
1549
  } catch {
1482
1550
  }
1551
+ this.crossfadeChain = [];
1483
1552
  this.emit(reason);
1484
1553
  this.resolveEnded();
1485
1554
  hook?.(this);
@@ -1515,6 +1584,81 @@ var Voice = class _Voice {
1515
1584
  if (!src.loop) this.finish("ended", hook);
1516
1585
  };
1517
1586
  }
1587
+ /**
1588
+ * Begin the loop-crossfade chain. Spawns the first segment immediately at
1589
+ * full level, then arms a setTimeout to spawn the next one shortly before
1590
+ * the boundary. Each subsequent spawn re-arms its own follow-up.
1591
+ *
1592
+ * Audio scheduling uses absolute `ctx.currentTime` values so drift between
1593
+ * setTimeout (wall clock) and the audio thread doesn't cause click-y
1594
+ * misalignment — setTimeout only needs to wake us in time to call
1595
+ * `source.start(when, ...)` before `when`.
1596
+ */
1597
+ startCrossfadeChain(when) {
1598
+ const first = this.spawnCrossfadeSegment(
1599
+ when,
1600
+ /* fadeIn */
1601
+ false
1602
+ );
1603
+ this.armNextCrossfadeSegment(when);
1604
+ return first.source;
1605
+ }
1606
+ spawnCrossfadeSegment(when, fadeIn) {
1607
+ const src = this.ctx.createBufferSource();
1608
+ src.buffer = this.buffer;
1609
+ src.loop = false;
1610
+ src.playbackRate.value = this.basePitch;
1611
+ const segGain = this.ctx.createGain();
1612
+ if (fadeIn) {
1613
+ segGain.gain.setValueAtTime(0, when);
1614
+ segGain.gain.linearRampToValueAtTime(1, when + this.crossfadeSec);
1615
+ } else {
1616
+ segGain.gain.setValueAtTime(1, when);
1617
+ }
1618
+ const fadeOutAt = when + this.crossfadeRegionLen - this.crossfadeSec;
1619
+ segGain.gain.setValueAtTime(1, fadeOutAt);
1620
+ segGain.gain.linearRampToValueAtTime(0, when + this.crossfadeRegionLen);
1621
+ src.connect(segGain).connect(this.gain);
1622
+ try {
1623
+ src.start(when, this.crossfadeRegionStart, this.crossfadeRegionLen);
1624
+ } catch {
1625
+ }
1626
+ src.onended = () => this.releaseCrossfadeSegment(src, segGain);
1627
+ const entry = { source: src, gain: segGain, startTime: when };
1628
+ this.crossfadeChain.push(entry);
1629
+ return entry;
1630
+ }
1631
+ armNextCrossfadeSegment(currentSegmentStart) {
1632
+ if (this.crossfadeArmTimer != null) {
1633
+ clearTimeout(this.crossfadeArmTimer);
1634
+ this.crossfadeArmTimer = null;
1635
+ }
1636
+ const nextStart = currentSegmentStart + this.crossfadeRegionLen - this.crossfadeSec;
1637
+ const SAFETY_LEAD_MS = 50;
1638
+ const delayMs = Math.max(0, (nextStart - this.ctx.currentTime) * 1e3 - SAFETY_LEAD_MS);
1639
+ this.crossfadeArmTimer = setTimeout(() => {
1640
+ this.crossfadeArmTimer = null;
1641
+ if (this.done || this.stopping || this.paused) return;
1642
+ this.spawnCrossfadeSegment(
1643
+ nextStart,
1644
+ /* fadeIn */
1645
+ true
1646
+ );
1647
+ this.armNextCrossfadeSegment(nextStart);
1648
+ }, delayMs);
1649
+ }
1650
+ releaseCrossfadeSegment(src, gain) {
1651
+ const idx = this.crossfadeChain.findIndex((e) => e.source === src);
1652
+ if (idx >= 0) this.crossfadeChain.splice(idx, 1);
1653
+ try {
1654
+ src.disconnect();
1655
+ gain.disconnect();
1656
+ } catch {
1657
+ }
1658
+ }
1659
+ get inCrossfadeMode() {
1660
+ return this.crossfadeSec > 0;
1661
+ }
1518
1662
  computeOffset() {
1519
1663
  if (this.paused) return this.pausedOffset;
1520
1664
  const elapsed = (this.ctx.currentTime - this.startCtxTime) * this.basePitch;
@@ -1973,6 +2117,47 @@ var EngineImpl = class {
1973
2117
  const urls = typeof url === "string" ? [url] : pickSourceOrder(url);
1974
2118
  return await this.decoder.loadFirst(urls, decodeOpts);
1975
2119
  }
2120
+ async preload(items, options = {}) {
2121
+ if (this.host.state === "closed") throw new EngineClosedError();
2122
+ if (items.length === 0) return;
2123
+ const concurrency = Math.max(1, options.concurrency ?? 4);
2124
+ const onProgress = options.onProgress;
2125
+ const batchSignal = options.signal;
2126
+ const total = items.length;
2127
+ let completed = 0;
2128
+ const failures = [];
2129
+ let nextIdx = 0;
2130
+ const workerCount = Math.min(concurrency, total);
2131
+ const workers = [];
2132
+ for (let w = 0; w < workerCount; w++) {
2133
+ workers.push(
2134
+ (async () => {
2135
+ while (true) {
2136
+ const idx = nextIdx++;
2137
+ if (idx >= total) return;
2138
+ if (batchSignal?.aborted) {
2139
+ throw batchSignal.reason ?? new DOMException("preload aborted", "AbortError");
2140
+ }
2141
+ const item = items[idx];
2142
+ const itemSignal = combineSignals(batchSignal, item.options?.signal);
2143
+ const opts = { ...item.options ?? {}, signal: itemSignal };
2144
+ try {
2145
+ await this.loadSound(item.name, item.url, opts);
2146
+ completed++;
2147
+ onProgress?.({ name: item.name, status: "loaded", completed, total });
2148
+ } catch (e) {
2149
+ if (e.name === "AbortError") throw e;
2150
+ completed++;
2151
+ failures.push({ name: item.name, cause: e });
2152
+ onProgress?.({ name: item.name, status: "failed", error: e, completed, total });
2153
+ }
2154
+ }
2155
+ })()
2156
+ );
2157
+ }
2158
+ await Promise.all(workers);
2159
+ if (failures.length > 0) throw new PreloadError(failures);
2160
+ }
1976
2161
  async loadSprite(name, url, regions, options = {}) {
1977
2162
  const sound = await this.loadSound(`__sprite:${name}`, url, options);
1978
2163
  const sprite = new Sprite(name, sound, regions);
@@ -2162,6 +2347,18 @@ function suggest(missing, candidates) {
2162
2347
  }
2163
2348
  return missing;
2164
2349
  }
2350
+ function combineSignals(a, b) {
2351
+ if (!a) return b;
2352
+ if (!b) return a;
2353
+ if (a.aborted) return a;
2354
+ if (b.aborted) return b;
2355
+ const ac = new AbortController();
2356
+ const onAbortA = () => ac.abort(a.reason);
2357
+ const onAbortB = () => ac.abort(b.reason);
2358
+ a.addEventListener("abort", onAbortA, { once: true });
2359
+ b.addEventListener("abort", onAbortB, { once: true });
2360
+ return ac.signal;
2361
+ }
2165
2362
  function levenshtein(a, b) {
2166
2363
  if (a === b) return 0;
2167
2364
  if (a.length === 0) return b.length;
@@ -2180,6 +2377,6 @@ function levenshtein(a, b) {
2180
2377
  return prev[b.length];
2181
2378
  }
2182
2379
 
2183
- export { AggregateDecodeError, Bus, BusNotFoundError, Compressor, DecodeError, Ducker, EngineClosedError, Filter, Master, Parameter, Reverb, Snapshot, Sound, SoundNotFoundError, Spatializer, Sprite, StreamSound, StretchProcessor, Voice, ZvukError, applyLoudnessNormalization, canPlay, computeNormalizationGain, createEngine, createStretchWorkletNode, ensureStretchWorklet, mimeForUrl, pickSource, pickSourceOrder };
2380
+ export { AggregateDecodeError, Bus, BusNotFoundError, Compressor, DecodeError, Ducker, EngineClosedError, Filter, Master, Parameter, PreloadError, Reverb, Snapshot, Sound, SoundNotFoundError, Spatializer, Sprite, StreamSound, StretchProcessor, Voice, ZvukError, applyLoudnessNormalization, canPlay, computeNormalizationGain, createEngine, createStretchWorkletNode, ensureStretchWorklet, mimeForUrl, pickSource, pickSourceOrder };
2184
2381
  //# sourceMappingURL=index.js.map
2185
2382
  //# sourceMappingURL=index.js.map