@schmooky/zvuk 1.3.0 → 1.5.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
@@ -10,9 +10,6 @@ declare class BusNotFoundError extends ZvukError {
10
10
  declare class SoundNotFoundError extends ZvukError {
11
11
  constructor(name: string);
12
12
  }
13
- declare class BankNotLoadedError extends ZvukError {
14
- constructor(id: string);
15
- }
16
13
  declare class DecodeError extends ZvukError {
17
14
  constructor(url: string, cause: unknown);
18
15
  }
@@ -286,6 +283,21 @@ interface PlayOptions {
286
283
  loopStart?: number;
287
284
  /** When loop=true, end of the loop region (seconds). */
288
285
  loopEnd?: number;
286
+ /**
287
+ * Equal-power crossfade duration (seconds) at the loop boundary. When
288
+ * `loop` is true and this is non-zero, zvuk spawns a parallel buffer
289
+ * source at every loop point and ramps between them — masking the click
290
+ * that AudioBufferSourceNode's native loop produces when the region
291
+ * doesn't end on a zero crossing.
292
+ *
293
+ * Default `0` (off — native hard-cut loop). Cost is one extra
294
+ * AudioBufferSourceNode + GainNode per loop iteration; with default
295
+ * Web Audio dispatch this is well under 1% CPU per voice.
296
+ *
297
+ * Ignored if `loop` is false, or if the loop region is shorter than
298
+ * twice the crossfade window (silent fallback to native loop).
299
+ */
300
+ loopCrossfade?: number;
289
301
  }
290
302
  interface LoudnessOptions$1 {
291
303
  /** Target RMS (linear, 0..1). Default 0.1 (~ -20 dBFS). */
@@ -373,8 +385,14 @@ declare class Voice {
373
385
  private loopEnd;
374
386
  private regionTimer;
375
387
  private stopFade;
388
+ private crossfadeSec;
389
+ private crossfadeRegionStart;
390
+ private crossfadeRegionLen;
391
+ private crossfadeChain;
392
+ private crossfadeArmTimer;
376
393
  static nextId: number;
377
394
  constructor(deps: VoiceDeps);
395
+ private shouldUseLoopCrossfade;
378
396
  fade(opts: FadeOptions): Promise<void>;
379
397
  /**
380
398
  * Stop the voice. Applies a short linear gain ramp (default ~8 ms) before
@@ -388,6 +406,8 @@ declare class Voice {
388
406
  * actually stops (i.e. after the ramp completes).
389
407
  */
390
408
  stop(opts?: StopOptions): void;
409
+ private activeSources;
410
+ private stopAllSources;
391
411
  /**
392
412
  * Pause this voice. Tracks the playback offset so resume() picks up
393
413
  * where it left off. No-op on a finished voice.
@@ -415,6 +435,21 @@ declare class Voice {
415
435
  private createSourceNode;
416
436
  private armRegionTimer;
417
437
  private bindSourceLifecycle;
438
+ /**
439
+ * Begin the loop-crossfade chain. Spawns the first segment immediately at
440
+ * full level, then arms a setTimeout to spawn the next one shortly before
441
+ * the boundary. Each subsequent spawn re-arms its own follow-up.
442
+ *
443
+ * Audio scheduling uses absolute `ctx.currentTime` values so drift between
444
+ * setTimeout (wall clock) and the audio thread doesn't cause click-y
445
+ * misalignment — setTimeout only needs to wake us in time to call
446
+ * `source.start(when, ...)` before `when`.
447
+ */
448
+ private startCrossfadeChain;
449
+ private spawnCrossfadeSegment;
450
+ private armNextCrossfadeSegment;
451
+ private releaseCrossfadeSegment;
452
+ private get inCrossfadeMode();
418
453
  private computeOffset;
419
454
  }
420
455
 
@@ -531,11 +566,16 @@ interface FilterConfig {
531
566
  /** Gain (dB) — only meaningful for `peaking`. Default 0. */
532
567
  gain?: number;
533
568
  }
569
+ /**
570
+ * Biquad filter as a bus FX insert. Bypass is a graph swap, not a parameter
571
+ * trick — when bypassed, input is connected directly to output, leaving the
572
+ * biquad fully detached so its delay-line state can't bleed into the dry
573
+ * signal.
574
+ */
534
575
  declare class Filter implements FxInsert {
535
- readonly input: BiquadFilterNode;
536
- readonly output: BiquadFilterNode;
537
- private bypassPath;
538
- private direct;
576
+ readonly input: GainNode;
577
+ readonly output: GainNode;
578
+ private filter;
539
579
  private ctx;
540
580
  private _bypassed;
541
581
  constructor(ctx: AudioContext, config?: FilterConfig);
@@ -545,6 +585,7 @@ declare class Filter implements FxInsert {
545
585
  get bypassed(): boolean;
546
586
  set bypassed(v: boolean);
547
587
  dispose(): void;
588
+ private wire;
548
589
  }
549
590
 
550
591
  interface ReverbConfig {
@@ -978,4 +1019,4 @@ type NormalizeFlag = boolean | LoudnessOptions;
978
1019
  declare function applyLoudnessNormalization(buffer: AudioBuffer, flag: NormalizeFlag): AudioBuffer;
979
1020
  declare function computeNormalizationGain(buffer: AudioBuffer, opts: Required<LoudnessOptions>): number;
980
1021
 
981
- export { AggregateDecodeError, type ApplyOptions, type AssetResolver, type AudioMimeType, BankNotLoadedError, 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 };
1022
+ 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 };
package/dist/index.js CHANGED
@@ -23,12 +23,6 @@ var SoundNotFoundError = class extends ZvukError {
23
23
  this.name = "SoundNotFoundError";
24
24
  }
25
25
  };
26
- var BankNotLoadedError = class extends ZvukError {
27
- constructor(id) {
28
- super(`Bank "${id}" is not loaded. Call engine.loadBank() before requesting its sounds.`);
29
- this.name = "BankNotLoadedError";
30
- }
31
- };
32
26
  var DecodeError = class extends ZvukError {
33
27
  constructor(url, cause) {
34
28
  super(`Failed to decode audio at "${url}": ${cause instanceof Error ? cause.message : String(cause)}`);
@@ -205,31 +199,28 @@ var Ducker = class {
205
199
  var Filter = class {
206
200
  input;
207
201
  output;
208
- bypassPath;
209
- direct;
202
+ filter;
210
203
  ctx;
211
204
  _bypassed = false;
212
205
  constructor(ctx, config = {}) {
213
206
  this.ctx = ctx;
214
- const node = ctx.createBiquadFilter();
215
- node.type = config.type ?? "lowpass";
216
- node.frequency.value = config.frequency ?? 1e3;
217
- node.Q.value = config.q ?? 1;
218
- node.gain.value = config.gain ?? 0;
219
- this.input = node;
220
- this.output = node;
221
- this.bypassPath = ctx.createGain();
222
- this.direct = ctx.createGain();
223
- this.direct.connect(node);
207
+ this.input = ctx.createGain();
208
+ this.output = ctx.createGain();
209
+ this.filter = ctx.createBiquadFilter();
210
+ this.filter.type = config.type ?? "lowpass";
211
+ this.filter.frequency.value = config.frequency ?? 1e3;
212
+ this.filter.Q.value = config.q ?? 1;
213
+ this.filter.gain.value = config.gain ?? 0;
214
+ this.wire();
224
215
  }
225
216
  setFrequency(hz) {
226
- this.input.frequency.setValueAtTime(hz, this.ctx.currentTime);
217
+ this.filter.frequency.setValueAtTime(hz, this.ctx.currentTime);
227
218
  }
228
219
  setQ(q) {
229
- this.input.Q.setValueAtTime(q, this.ctx.currentTime);
220
+ this.filter.Q.setValueAtTime(q, this.ctx.currentTime);
230
221
  }
231
222
  setType(t) {
232
- this.input.type = t;
223
+ this.filter.type = t;
233
224
  }
234
225
  get bypassed() {
235
226
  return this._bypassed;
@@ -237,15 +228,28 @@ var Filter = class {
237
228
  set bypassed(v) {
238
229
  if (this._bypassed === v) return;
239
230
  this._bypassed = v;
240
- this.input.frequency.value = v ? 22050 : this.input.frequency.value || 1e3;
231
+ this.wire();
241
232
  }
242
233
  dispose() {
243
234
  try {
244
235
  this.input.disconnect();
245
- this.bypassPath.disconnect();
246
- this.direct.disconnect();
236
+ this.filter.disconnect();
237
+ this.output.disconnect();
238
+ } catch {
239
+ }
240
+ }
241
+ wire() {
242
+ try {
243
+ this.input.disconnect();
244
+ this.filter.disconnect();
247
245
  } catch {
248
246
  }
247
+ if (this._bypassed) {
248
+ this.input.connect(this.output);
249
+ } else {
250
+ this.input.connect(this.filter);
251
+ this.filter.connect(this.output);
252
+ }
249
253
  }
250
254
  };
251
255
 
@@ -743,7 +747,18 @@ function wait(seconds) {
743
747
  if (seconds <= 0) return Promise.resolve();
744
748
  return new Promise((res) => setTimeout(res, seconds * 1e3));
745
749
  }
750
+ var warnedQuietest = false;
746
751
  function pickVictim(voices, strategy, newVoice) {
752
+ let effective = strategy;
753
+ if (effective === "quietest") {
754
+ if (!warnedQuietest) {
755
+ warnedQuietest = true;
756
+ console.warn(
757
+ "[zvuk] concurrency.steal: 'quietest' currently falls back to 'oldest' \u2014 per-voice level metering ships in a follow-up release. Use 'lowest-priority' if you need explicit control today."
758
+ );
759
+ }
760
+ effective = "oldest";
761
+ }
747
762
  let victim = null;
748
763
  for (const v of voices) {
749
764
  if (v === newVoice) continue;
@@ -751,16 +766,13 @@ function pickVictim(voices, strategy, newVoice) {
751
766
  victim = v;
752
767
  continue;
753
768
  }
754
- switch (strategy) {
769
+ switch (effective) {
755
770
  case "oldest":
756
771
  if (v.startedAt < victim.startedAt) victim = v;
757
772
  break;
758
773
  case "lowest-priority":
759
774
  if (v.priority < victim.priority) victim = v;
760
775
  break;
761
- case "quietest":
762
- if (v.startedAt < victim.startedAt) victim = v;
763
- break;
764
776
  }
765
777
  }
766
778
  return victim;
@@ -1252,6 +1264,15 @@ var Voice = class _Voice {
1252
1264
  loopEnd;
1253
1265
  regionTimer = null;
1254
1266
  stopFade;
1267
+ // Loop-crossfade state. Inactive when crossfadeSec === 0.
1268
+ // In crossfade mode, `source` is the most-recently-armed segment and the
1269
+ // `crossfadeChain` carries every segment currently scheduled or live so
1270
+ // that stop/pause/setPlaybackRate can fan out across them.
1271
+ crossfadeSec = 0;
1272
+ crossfadeRegionStart = 0;
1273
+ crossfadeRegionLen = 0;
1274
+ crossfadeChain = [];
1275
+ crossfadeArmTimer = null;
1255
1276
  static nextId = 1;
1256
1277
  constructor(deps) {
1257
1278
  const { ctx, buffer, destination, options } = deps;
@@ -1275,13 +1296,10 @@ var Voice = class _Voice {
1275
1296
  const initialVolume = resolveJittered(options.volume ?? 1);
1276
1297
  this.gain.gain.value = clamp012(initialVolume);
1277
1298
  this.gain.connect(destination);
1278
- this.source = this.createSourceNode(this.basePitch);
1279
1299
  this.startCtxTime = ctx.currentTime;
1280
1300
  this.ended = new Promise((resolve) => {
1281
1301
  this.resolveEnded = resolve;
1282
1302
  });
1283
- this.bindSourceLifecycle(this.source, () => {
1284
- });
1285
1303
  if (options.signal) {
1286
1304
  if (options.signal.aborted) {
1287
1305
  queueMicrotask(() => this.stop());
@@ -1289,14 +1307,34 @@ var Voice = class _Voice {
1289
1307
  options.signal.addEventListener("abort", () => this.stop(), { once: true });
1290
1308
  }
1291
1309
  }
1292
- try {
1293
- this.source.start(0, this.startOffset);
1294
- } catch {
1310
+ if (this.shouldUseLoopCrossfade(options)) {
1311
+ this.crossfadeSec = options.loopCrossfade;
1312
+ this.crossfadeRegionStart = options.loopStart ?? this.startOffset;
1313
+ const regionEnd = options.loopEnd ?? buffer.duration;
1314
+ this.crossfadeRegionLen = Math.max(0, regionEnd - this.crossfadeRegionStart);
1315
+ this.source = this.startCrossfadeChain(ctx.currentTime);
1316
+ } else {
1317
+ this.source = this.createSourceNode(this.basePitch);
1318
+ this.bindSourceLifecycle(this.source, () => {
1319
+ });
1320
+ try {
1321
+ this.source.start(0, this.startOffset);
1322
+ } catch {
1323
+ }
1324
+ this.armRegionTimer(this.regionDuration);
1295
1325
  }
1296
- this.armRegionTimer(this.regionDuration);
1297
1326
  queueMicrotask(() => this.emit("started"));
1298
1327
  void this.ended.then(() => deps.onEnded(this));
1299
1328
  }
1329
+ shouldUseLoopCrossfade(options) {
1330
+ if (!this.loop) return false;
1331
+ const cf = options.loopCrossfade;
1332
+ if (cf == null || cf <= 0) return false;
1333
+ const start = options.loopStart ?? this.startOffset;
1334
+ const end = options.loopEnd ?? this.buffer.duration;
1335
+ const len = end - start;
1336
+ return len > cf * 2;
1337
+ }
1300
1338
  fade(opts) {
1301
1339
  const param = this.gain.gain;
1302
1340
  const now = this.ctx.currentTime;
@@ -1317,18 +1355,19 @@ var Voice = class _Voice {
1317
1355
  stop(opts = {}) {
1318
1356
  if (this.done || this.stopping) return;
1319
1357
  const fade = Math.max(0, opts.fade ?? this.stopFade);
1358
+ if (this.crossfadeArmTimer != null) {
1359
+ clearTimeout(this.crossfadeArmTimer);
1360
+ this.crossfadeArmTimer = null;
1361
+ }
1320
1362
  if (fade === 0) {
1321
- try {
1322
- this.source.stop();
1323
- } catch {
1324
- }
1363
+ this.stopAllSources(0);
1325
1364
  this.finish("ended");
1326
1365
  return;
1327
1366
  }
1328
1367
  this.stopping = true;
1329
1368
  const now = this.ctx.currentTime;
1330
1369
  const stopAt = now + fade;
1331
- this.source.onended = null;
1370
+ for (const src of this.activeSources()) src.onended = null;
1332
1371
  if (this.regionTimer != null) {
1333
1372
  clearTimeout(this.regionTimer);
1334
1373
  this.regionTimer = null;
@@ -1338,13 +1377,26 @@ var Voice = class _Voice {
1338
1377
  param.cancelScheduledValues(now);
1339
1378
  param.setValueAtTime(param.value, now);
1340
1379
  param.linearRampToValueAtTime(0, stopAt);
1341
- this.source.stop(stopAt);
1380
+ this.stopAllSources(stopAt);
1342
1381
  } catch {
1343
1382
  this.finish("ended");
1344
1383
  return;
1345
1384
  }
1346
1385
  setTimeout(() => this.finish("ended"), fade * 1e3);
1347
1386
  }
1387
+ activeSources() {
1388
+ if (this.inCrossfadeMode) return this.crossfadeChain.map((e) => e.source);
1389
+ return [this.source];
1390
+ }
1391
+ stopAllSources(when) {
1392
+ for (const src of this.activeSources()) {
1393
+ try {
1394
+ if (when === 0) src.stop();
1395
+ else src.stop(when);
1396
+ } catch {
1397
+ }
1398
+ }
1399
+ }
1348
1400
  /**
1349
1401
  * Pause this voice. Tracks the playback offset so resume() picks up
1350
1402
  * where it left off. No-op on a finished voice.
@@ -1359,33 +1411,44 @@ var Voice = class _Voice {
1359
1411
  clearTimeout(this.regionTimer);
1360
1412
  this.regionTimer = null;
1361
1413
  }
1362
- try {
1363
- this.source.onended = null;
1364
- this.source.stop();
1365
- } catch {
1414
+ if (this.crossfadeArmTimer != null) {
1415
+ clearTimeout(this.crossfadeArmTimer);
1416
+ this.crossfadeArmTimer = null;
1366
1417
  }
1367
- try {
1368
- this.source.disconnect();
1369
- } catch {
1418
+ for (const src of this.activeSources()) {
1419
+ try {
1420
+ src.onended = null;
1421
+ src.stop();
1422
+ } catch {
1423
+ }
1424
+ try {
1425
+ src.disconnect();
1426
+ } catch {
1427
+ }
1370
1428
  }
1429
+ if (this.inCrossfadeMode) this.crossfadeChain = [];
1371
1430
  this.emit("paused");
1372
1431
  }
1373
1432
  /** Resume from the offset captured on pause(). No-op when not paused. */
1374
1433
  resume() {
1375
1434
  if (this.done || !this.paused) return;
1376
1435
  this.paused = false;
1377
- this.source = this.createSourceNode(this.basePitch);
1378
- this.bindSourceLifecycle(this.source, () => {
1379
- });
1380
1436
  this.startCtxTime = this.ctx.currentTime;
1381
- try {
1382
- this.source.start(0, this.pausedOffset);
1383
- } catch {
1384
- }
1385
- if (this.regionDuration != null) {
1386
- const consumed = Math.max(0, this.pausedOffset - this.startOffset);
1387
- const remaining = Math.max(0, this.regionDuration - consumed);
1388
- this.armRegionTimer(remaining);
1437
+ if (this.inCrossfadeMode) {
1438
+ this.source = this.startCrossfadeChain(this.startCtxTime);
1439
+ } else {
1440
+ this.source = this.createSourceNode(this.basePitch);
1441
+ this.bindSourceLifecycle(this.source, () => {
1442
+ });
1443
+ try {
1444
+ this.source.start(0, this.pausedOffset);
1445
+ } catch {
1446
+ }
1447
+ if (this.regionDuration != null) {
1448
+ const consumed = Math.max(0, this.pausedOffset - this.startOffset);
1449
+ const remaining = Math.max(0, this.regionDuration - consumed);
1450
+ this.armRegionTimer(remaining);
1451
+ }
1389
1452
  }
1390
1453
  this.emit("resumed");
1391
1454
  }
@@ -1407,12 +1470,14 @@ var Voice = class _Voice {
1407
1470
  }
1408
1471
  this.basePitch = r;
1409
1472
  if (this.paused) return;
1410
- const param = this.source.playbackRate;
1411
- if (duration === 0) {
1412
- param.value = r;
1413
- return;
1473
+ for (const src of this.activeSources()) {
1474
+ const param = src.playbackRate;
1475
+ if (duration === 0) {
1476
+ param.value = r;
1477
+ } else {
1478
+ applyRamp(param, this.ctx.currentTime, r, duration, opts.curve ?? "linear");
1479
+ }
1414
1480
  }
1415
- applyRamp(param, this.ctx.currentTime, r, duration, opts.curve ?? "linear");
1416
1481
  }
1417
1482
  get playbackRate() {
1418
1483
  return this.basePitch;
@@ -1463,11 +1528,17 @@ var Voice = class _Voice {
1463
1528
  clearTimeout(this.regionTimer);
1464
1529
  this.regionTimer = null;
1465
1530
  }
1531
+ if (this.crossfadeArmTimer != null) {
1532
+ clearTimeout(this.crossfadeArmTimer);
1533
+ this.crossfadeArmTimer = null;
1534
+ }
1466
1535
  try {
1467
- this.source.disconnect();
1536
+ for (const src of this.activeSources()) src.disconnect();
1537
+ for (const e of this.crossfadeChain) e.gain.disconnect();
1468
1538
  this.gain.disconnect();
1469
1539
  } catch {
1470
1540
  }
1541
+ this.crossfadeChain = [];
1471
1542
  this.emit(reason);
1472
1543
  this.resolveEnded();
1473
1544
  hook?.(this);
@@ -1503,6 +1574,81 @@ var Voice = class _Voice {
1503
1574
  if (!src.loop) this.finish("ended", hook);
1504
1575
  };
1505
1576
  }
1577
+ /**
1578
+ * Begin the loop-crossfade chain. Spawns the first segment immediately at
1579
+ * full level, then arms a setTimeout to spawn the next one shortly before
1580
+ * the boundary. Each subsequent spawn re-arms its own follow-up.
1581
+ *
1582
+ * Audio scheduling uses absolute `ctx.currentTime` values so drift between
1583
+ * setTimeout (wall clock) and the audio thread doesn't cause click-y
1584
+ * misalignment — setTimeout only needs to wake us in time to call
1585
+ * `source.start(when, ...)` before `when`.
1586
+ */
1587
+ startCrossfadeChain(when) {
1588
+ const first = this.spawnCrossfadeSegment(
1589
+ when,
1590
+ /* fadeIn */
1591
+ false
1592
+ );
1593
+ this.armNextCrossfadeSegment(when);
1594
+ return first.source;
1595
+ }
1596
+ spawnCrossfadeSegment(when, fadeIn) {
1597
+ const src = this.ctx.createBufferSource();
1598
+ src.buffer = this.buffer;
1599
+ src.loop = false;
1600
+ src.playbackRate.value = this.basePitch;
1601
+ const segGain = this.ctx.createGain();
1602
+ if (fadeIn) {
1603
+ segGain.gain.setValueAtTime(0, when);
1604
+ segGain.gain.linearRampToValueAtTime(1, when + this.crossfadeSec);
1605
+ } else {
1606
+ segGain.gain.setValueAtTime(1, when);
1607
+ }
1608
+ const fadeOutAt = when + this.crossfadeRegionLen - this.crossfadeSec;
1609
+ segGain.gain.setValueAtTime(1, fadeOutAt);
1610
+ segGain.gain.linearRampToValueAtTime(0, when + this.crossfadeRegionLen);
1611
+ src.connect(segGain).connect(this.gain);
1612
+ try {
1613
+ src.start(when, this.crossfadeRegionStart, this.crossfadeRegionLen);
1614
+ } catch {
1615
+ }
1616
+ src.onended = () => this.releaseCrossfadeSegment(src, segGain);
1617
+ const entry = { source: src, gain: segGain, startTime: when };
1618
+ this.crossfadeChain.push(entry);
1619
+ return entry;
1620
+ }
1621
+ armNextCrossfadeSegment(currentSegmentStart) {
1622
+ if (this.crossfadeArmTimer != null) {
1623
+ clearTimeout(this.crossfadeArmTimer);
1624
+ this.crossfadeArmTimer = null;
1625
+ }
1626
+ const nextStart = currentSegmentStart + this.crossfadeRegionLen - this.crossfadeSec;
1627
+ const SAFETY_LEAD_MS = 50;
1628
+ const delayMs = Math.max(0, (nextStart - this.ctx.currentTime) * 1e3 - SAFETY_LEAD_MS);
1629
+ this.crossfadeArmTimer = setTimeout(() => {
1630
+ this.crossfadeArmTimer = null;
1631
+ if (this.done || this.stopping || this.paused) return;
1632
+ this.spawnCrossfadeSegment(
1633
+ nextStart,
1634
+ /* fadeIn */
1635
+ true
1636
+ );
1637
+ this.armNextCrossfadeSegment(nextStart);
1638
+ }, delayMs);
1639
+ }
1640
+ releaseCrossfadeSegment(src, gain) {
1641
+ const idx = this.crossfadeChain.findIndex((e) => e.source === src);
1642
+ if (idx >= 0) this.crossfadeChain.splice(idx, 1);
1643
+ try {
1644
+ src.disconnect();
1645
+ gain.disconnect();
1646
+ } catch {
1647
+ }
1648
+ }
1649
+ get inCrossfadeMode() {
1650
+ return this.crossfadeSec > 0;
1651
+ }
1506
1652
  computeOffset() {
1507
1653
  if (this.paused) return this.pausedOffset;
1508
1654
  const elapsed = (this.ctx.currentTime - this.startCtxTime) * this.basePitch;
@@ -2168,6 +2314,6 @@ function levenshtein(a, b) {
2168
2314
  return prev[b.length];
2169
2315
  }
2170
2316
 
2171
- export { AggregateDecodeError, BankNotLoadedError, 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 };
2317
+ 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 };
2172
2318
  //# sourceMappingURL=index.js.map
2173
2319
  //# sourceMappingURL=index.js.map