@schmooky/zvuk 0.0.0-develop-20260503095453

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.
@@ -0,0 +1,798 @@
1
+ declare class ZvukError extends Error {
2
+ constructor(message: string);
3
+ }
4
+ declare class EngineClosedError extends ZvukError {
5
+ constructor();
6
+ }
7
+ declare class BusNotFoundError extends ZvukError {
8
+ constructor(name: string);
9
+ }
10
+ declare class SoundNotFoundError extends ZvukError {
11
+ constructor(name: string);
12
+ }
13
+ declare class BankNotLoadedError extends ZvukError {
14
+ constructor(id: string);
15
+ }
16
+ declare class DecodeError extends ZvukError {
17
+ constructor(url: string, cause: unknown);
18
+ }
19
+
20
+ /**
21
+ * Common FX insert contract. Every FX exposes a single input + a single
22
+ * output node so the bus can splice it into the (fxInput → output) hop.
23
+ */
24
+ interface FxInsert {
25
+ readonly input: AudioNode;
26
+ readonly output: AudioNode;
27
+ bypassed: boolean;
28
+ dispose(): void;
29
+ }
30
+
31
+ interface CompressorConfig {
32
+ /** dB at which compression begins. Default -24. */
33
+ threshold?: number;
34
+ /** dB range over which the curve smoothly transitions into compression. Default 30. */
35
+ knee?: number;
36
+ /** Compression ratio. Default 12. */
37
+ ratio?: number;
38
+ /** Attack time in seconds. Default 0.003. */
39
+ attack?: number;
40
+ /** Release time in seconds. Default 0.25. */
41
+ release?: number;
42
+ /** Make-up gain in dB applied after compression. Default 0. */
43
+ makeupGain?: number;
44
+ }
45
+ /**
46
+ * Dynamics compressor as a bus FX insert. Wraps DynamicsCompressorNode and a
47
+ * make-up gain node, and exposes `input`/`output` so the Bus can wire it into
48
+ * its FX chain. Bypass is a graph swap, not a parameter — when bypassed, the
49
+ * input is connected directly to the output (avoids the compressor's
50
+ * non-zero look-ahead latency leaking into the dry signal).
51
+ */
52
+ declare class Compressor implements FxInsert {
53
+ readonly input: GainNode;
54
+ readonly output: GainNode;
55
+ private compressor;
56
+ private makeup;
57
+ private ctx;
58
+ private _bypassed;
59
+ constructor(ctx: AudioContext, config?: CompressorConfig);
60
+ applyConfig(c: CompressorConfig): void;
61
+ /** Live gain reduction in dB (read-only, negative when compressing). */
62
+ get reduction(): number;
63
+ get bypassed(): boolean;
64
+ set bypassed(v: boolean);
65
+ dispose(): void;
66
+ private wire;
67
+ }
68
+
69
+ type FadeCurve = 'linear' | 'equal-power' | 'easeIn' | 'easeOut' | 'easeInOut';
70
+ interface ConcurrencyConfig {
71
+ /** Max simultaneous voices on this bus. */
72
+ max: number;
73
+ /** Voice-stealing strategy when max is reached. Default: 'oldest'. */
74
+ steal?: 'oldest' | 'lowest-priority' | 'quietest' | 'none';
75
+ }
76
+ interface SidechainConfig {
77
+ /** Bus name to listen to. When that bus is loud, this bus is ducked. */
78
+ from: string;
79
+ /** Amount of duck (0..1, where 1 = fully muted at peak source). */
80
+ amount: number;
81
+ /** Attack ms. */
82
+ attack?: number;
83
+ /** Release ms. */
84
+ release?: number;
85
+ }
86
+ interface BusConfig {
87
+ level?: number;
88
+ mute?: boolean;
89
+ concurrency?: ConcurrencyConfig;
90
+ sidechain?: SidechainConfig;
91
+ }
92
+ interface MasterLimiterConfig {
93
+ /** Threshold in dB. Default -1 (just below 0 dBFS). */
94
+ threshold?: number;
95
+ /** Compression ratio. Default 20 (brick-wall). */
96
+ ratio?: number;
97
+ /** Attack in seconds. Default 0.001 (fast — catches the transient). */
98
+ attack?: number;
99
+ /** Release in seconds. Default 0.05. */
100
+ release?: number;
101
+ }
102
+ interface MasterConfig {
103
+ /** Headroom in dB applied to the master gain (negative). Default: 0. */
104
+ headroom?: number;
105
+ /** Optional brick-wall limiter on the master output. */
106
+ limiter?: MasterLimiterConfig;
107
+ }
108
+ interface EngineConfig {
109
+ buses?: Record<string, BusConfig>;
110
+ master?: MasterConfig;
111
+ }
112
+ interface FadeOptions {
113
+ to: number;
114
+ ms: number;
115
+ curve?: FadeCurve;
116
+ }
117
+ interface VoiceJitter {
118
+ jitter?: number;
119
+ }
120
+ interface SpatialOptions {
121
+ /** [-1, 1] stereo pan (2D). Mutually exclusive with `position`. */
122
+ pan?: number;
123
+ /** [x, y, z] world-space position (3D). Mutually exclusive with `pan`. */
124
+ position?: [number, number, number];
125
+ }
126
+ interface PlayOptions {
127
+ /** Initial volume (0..1). Default 1. */
128
+ volume?: number | VoiceJitter;
129
+ /** Playback rate. 1 = source speed. Random jitter optional. */
130
+ pitch?: number | VoiceJitter;
131
+ /** Loop the voice. Default false. */
132
+ loop?: boolean;
133
+ /** Override the default bus for this voice. */
134
+ bus?: string;
135
+ /** Voice priority — higher = more likely to survive stealing. Default 0. */
136
+ priority?: number;
137
+ /** AbortSignal — voice stops when aborted. */
138
+ signal?: AbortSignal;
139
+ /** 2D pan or 3D position. Inserts a Spatializer between the voice and its bus. */
140
+ spatializer?: SpatialOptions;
141
+ /** Offset into the buffer (seconds) to start at. Default 0. Used by Sprite. */
142
+ offset?: number;
143
+ /** If set, voice auto-stops after this many seconds. Used by Sprite. */
144
+ duration?: number;
145
+ /** When loop=true, start of the loop region (seconds). */
146
+ loopStart?: number;
147
+ /** When loop=true, end of the loop region (seconds). */
148
+ loopEnd?: number;
149
+ }
150
+ interface LoudnessOptions$1 {
151
+ /** Target RMS (linear, 0..1). Default 0.1 (~ -20 dBFS). */
152
+ targetRms?: number;
153
+ /** Hard ceiling for the resulting peak; gain is reduced to stay below it. Default 0.99. */
154
+ peakCeiling?: number;
155
+ }
156
+ interface LoadSoundOptions {
157
+ /** Default bus for voices spawned by this sound. Default: first declared bus. */
158
+ bus?: string;
159
+ /** AbortSignal for the fetch. */
160
+ signal?: AbortSignal;
161
+ /**
162
+ * Run RMS-based loudness normalization on the decoded buffer so it sits at
163
+ * the same perceived loudness as other normalized sounds. Pass `true` for
164
+ * defaults or an options object to tune the target.
165
+ */
166
+ normalize?: boolean | LoudnessOptions$1;
167
+ }
168
+
169
+ /**
170
+ * PannerNode wrapper. Inserted between a Voice and its Bus when a play call
171
+ * passes a `spatializer` option. 2D pan uses StereoPannerNode (cheap), 3D
172
+ * uses PannerNode in HRTF mode (one node per voice — fine for the dozens
173
+ * of simultaneous voices a typical game holds, expensive past hundreds).
174
+ */
175
+ declare class Spatializer {
176
+ private node;
177
+ private kind;
178
+ constructor(ctx: AudioContext, opts: SpatialOptions);
179
+ setPan(pan: number): void;
180
+ setPosition(x: number, y: number, z: number): void;
181
+ /** Connects internal node into `dest` and returns the input the Voice should use. */
182
+ connectInto(dest: AudioNode): AudioNode;
183
+ dispose(): void;
184
+ private setPanner3D;
185
+ }
186
+
187
+ type VoiceCue = 'started' | 'paused' | 'resumed' | 'ended';
188
+ interface VoiceDeps {
189
+ ctx: AudioContext;
190
+ buffer: AudioBuffer;
191
+ destination: AudioNode;
192
+ options: PlayOptions;
193
+ onEnded: (v: Voice) => void;
194
+ spatializer?: Spatializer;
195
+ sourceName?: string;
196
+ }
197
+ /**
198
+ * One playback instance, returned from sound.play(). Owns its source node
199
+ * and gain stage; disposes itself on natural end, signal abort, or stop().
200
+ *
201
+ * Voice constructor is package-private — callers obtain instances via
202
+ * Sound.play().
203
+ */
204
+ declare class Voice {
205
+ readonly id: number;
206
+ readonly priority: number;
207
+ readonly bus: string | undefined;
208
+ readonly startedAt: number;
209
+ /** Name of the Sound that spawned this voice (if any). Used for crossfade. */
210
+ readonly sourceName: string | undefined;
211
+ /** Resolves when playback finishes (natural end, stop(), or abort). */
212
+ readonly ended: Promise<void>;
213
+ private ctx;
214
+ private gain;
215
+ private source;
216
+ private buffer;
217
+ private loop;
218
+ private basePitch;
219
+ private done;
220
+ private paused;
221
+ private resolveEnded;
222
+ private cueListeners;
223
+ private startCtxTime;
224
+ private pausedOffset;
225
+ private currentOffset;
226
+ private _spatializer;
227
+ private startOffset;
228
+ private regionDuration;
229
+ private loopStart;
230
+ private loopEnd;
231
+ private regionTimer;
232
+ static nextId: number;
233
+ constructor(deps: VoiceDeps);
234
+ fade(opts: FadeOptions): Promise<void>;
235
+ stop(): void;
236
+ /**
237
+ * Pause this voice. Tracks the playback offset so resume() picks up
238
+ * where it left off. No-op on a finished voice.
239
+ */
240
+ pause(): void;
241
+ /** Resume from the offset captured on pause(). No-op when not paused. */
242
+ resume(): void;
243
+ /** Whether the voice is currently paused (and thus retaining its offset). */
244
+ get isPaused(): boolean;
245
+ /**
246
+ * Live playback-rate setter. Optional ramp via curve.
247
+ * Setting while paused only updates the value used on the next start.
248
+ */
249
+ setPlaybackRate(rate: number, opts?: {
250
+ ms?: number;
251
+ curve?: FadeOptions['curve'];
252
+ }): void;
253
+ get playbackRate(): number;
254
+ /** The Spatializer attached to this voice (if any). Use for live setPan/setPosition. */
255
+ get spatializer(): Spatializer | undefined;
256
+ /** Async iterator of lifecycle cues — yields started, optional paused, ended. */
257
+ cues(): AsyncIterableIterator<VoiceCue>;
258
+ private finish;
259
+ private emit;
260
+ private createSourceNode;
261
+ private armRegionTimer;
262
+ private bindSourceLifecycle;
263
+ private computeOffset;
264
+ }
265
+
266
+ /**
267
+ * A Bus is a named mix bucket with its own gain stage, optional FX inserts,
268
+ * a voice-concurrency limit, and an optional sidechain key.
269
+ *
270
+ * Voices are connected to bus.input. The master receives bus.output.
271
+ *
272
+ * level/mute use 10ms ramps to avoid clicks; raw gain.value writes would
273
+ * pop audibly on browsers that don't smooth the parameter.
274
+ */
275
+ declare class Bus {
276
+ readonly name: string;
277
+ readonly input: GainNode;
278
+ /** Sub-bus where FX inserts go. Currently == input; reserved for FX chain. */
279
+ readonly fxInput: GainNode;
280
+ /** Output node — connect to master.input or another bus.input for sends. */
281
+ readonly output: GainNode;
282
+ private _level;
283
+ private _muted;
284
+ private _baseLevel;
285
+ private readonly ctx;
286
+ private _concurrency;
287
+ private _voices;
288
+ private _fxChain;
289
+ constructor(ctx: AudioContext, name: string, config?: BusConfig);
290
+ get level(): number;
291
+ set level(v: number);
292
+ get muted(): boolean;
293
+ set muted(v: boolean);
294
+ fadeTo(target: number, durationMs: number, curve?: FadeCurve): Promise<void>;
295
+ /** Active voice count on this bus. */
296
+ get voiceCount(): number;
297
+ /** Read-only iterator over active voices. */
298
+ voices(): readonly Voice[];
299
+ /** Concurrency config — read it for UI, mutate via setConcurrency. */
300
+ get concurrency(): ConcurrencyConfig | null;
301
+ setConcurrency(c: ConcurrencyConfig | null): void;
302
+ /**
303
+ * Called by Engine right before adding a new Voice. Returns a Voice that
304
+ * was stolen to make room (so the engine can release it from its tracking),
305
+ * or null if no steal was needed (or the new voice itself was rejected,
306
+ * in which case onReject is invoked instead).
307
+ */
308
+ applyConcurrencyOnSpawn(newVoice: Voice, onReject: () => void): Voice | null;
309
+ /** Engine-only: register an active voice. */
310
+ trackVoice(v: Voice): void;
311
+ /** Engine-only: deregister a finished voice. */
312
+ releaseVoice(v: Voice): void;
313
+ /** Add an FX insert to the bus's FX chain (post-input, pre-output). */
314
+ addFx(fx: FxInsert): void;
315
+ removeFx(fx: FxInsert): void;
316
+ fx(): readonly FxInsert[];
317
+ private rewireFxChain;
318
+ private rampOutput;
319
+ private ramp;
320
+ dispose(): void;
321
+ }
322
+
323
+ interface DuckerConfig {
324
+ /** How much to attenuate when fully ducking (0..1). Default 0.5 = -6 dB. */
325
+ amount?: number;
326
+ /** Attack ms. Default 80. */
327
+ attack?: number;
328
+ /** Release ms. Default 400. */
329
+ release?: number;
330
+ /** Threshold (linear amplitude) on the source bus's RMS to trigger ducking. Default 0.05. */
331
+ threshold?: number;
332
+ }
333
+ /**
334
+ * Sidechain ducker. Inserts on the *target* bus (e.g. music) and listens to
335
+ * the level of a source bus (e.g. voice). When the source is loud, the
336
+ * target's gain drops; when quiet, it returns.
337
+ *
338
+ * Implementation: an envelope follower running on the source bus's RMS,
339
+ * driving an additional gain node spliced into the target's FX chain.
340
+ *
341
+ * The envelope follower runs on the main thread at ~60 Hz — fine for a
342
+ * speech ducker, not for sample-accurate audio-rate sidechaining. For that,
343
+ * use a custom AudioWorklet (planned).
344
+ */
345
+ declare class Ducker implements FxInsert {
346
+ readonly input: GainNode;
347
+ readonly output: GainNode;
348
+ private gain;
349
+ private analyser;
350
+ private buf;
351
+ private rafId;
352
+ private envelope;
353
+ private targetGain;
354
+ private ctx;
355
+ private cfg;
356
+ private _bypassed;
357
+ constructor(ctx: AudioContext, sourceBus: Bus, config?: DuckerConfig);
358
+ setAmount(a: number): void;
359
+ setThreshold(t: number): void;
360
+ get bypassed(): boolean;
361
+ set bypassed(v: boolean);
362
+ dispose(): void;
363
+ private tick;
364
+ }
365
+
366
+ type FilterKind = 'lowpass' | 'highpass' | 'bandpass' | 'notch' | 'peaking' | 'allpass';
367
+ interface FilterConfig {
368
+ type?: FilterKind;
369
+ /** Cutoff/center frequency in Hz. Default 1000. */
370
+ frequency?: number;
371
+ /** Q factor (resonance). Default 1. */
372
+ q?: number;
373
+ /** Gain (dB) — only meaningful for `peaking`. Default 0. */
374
+ gain?: number;
375
+ }
376
+ declare class Filter implements FxInsert {
377
+ readonly input: BiquadFilterNode;
378
+ readonly output: BiquadFilterNode;
379
+ private bypassPath;
380
+ private direct;
381
+ private ctx;
382
+ private _bypassed;
383
+ constructor(ctx: AudioContext, config?: FilterConfig);
384
+ setFrequency(hz: number): void;
385
+ setQ(q: number): void;
386
+ setType(t: FilterKind): void;
387
+ get bypassed(): boolean;
388
+ set bypassed(v: boolean);
389
+ dispose(): void;
390
+ }
391
+
392
+ interface ReverbConfig {
393
+ /** Wet/dry mix (0 = dry, 1 = full wet). Default 0.3. */
394
+ wet?: number;
395
+ /** A loaded impulse-response buffer. If omitted, a synthetic decay is generated. */
396
+ impulse?: AudioBuffer;
397
+ /** Synthetic decay parameters (used when `impulse` is omitted). */
398
+ decay?: {
399
+ /** RT60-style decay in seconds. Default 1.5. */
400
+ seconds?: number;
401
+ /** Pre-delay in seconds. Default 0. */
402
+ preDelay?: number;
403
+ };
404
+ }
405
+ /**
406
+ * Convolution reverb. Mixes a dry signal with a wet path that runs through
407
+ * a ConvolverNode. If no impulse response is provided, a synthetic noise
408
+ * decay is generated — quick and free, but not as nice as a real IR.
409
+ */
410
+ declare class Reverb implements FxInsert {
411
+ readonly input: GainNode;
412
+ readonly output: GainNode;
413
+ private dry;
414
+ private wet;
415
+ private convolver;
416
+ private preDelay;
417
+ private ctx;
418
+ private _bypassed;
419
+ constructor(ctx: AudioContext, config?: ReverbConfig);
420
+ setWet(mix: number): void;
421
+ setImpulse(buffer: AudioBuffer): void;
422
+ get bypassed(): boolean;
423
+ set bypassed(v: boolean);
424
+ dispose(): void;
425
+ /** Generate a synthetic exponential-decay impulse response. */
426
+ private synthIR;
427
+ }
428
+
429
+ /**
430
+ * Pitch-preserving time-stretch via overlap-add granular synthesis with
431
+ * cross-correlation alignment (a SOLA-style approximation).
432
+ *
433
+ * Used to render an offline stretched copy of an AudioBuffer at load time —
434
+ * not realtime. For realtime tempo control, see the (planned) AudioWorklet
435
+ * implementation.
436
+ *
437
+ * stretchFactor > 1 = play faster (shorter buffer).
438
+ * stretchFactor < 1 = not currently supported (use rate via PlaybackRate).
439
+ */
440
+ declare class StretchProcessor {
441
+ private factor;
442
+ constructor(stretchFactor?: number);
443
+ process(input: Float32Array): Float32Array;
444
+ /** Convenience: process an AudioBuffer in place to a new buffer. */
445
+ static stretchBuffer(ctx: BaseAudioContext, src: AudioBuffer, factor: number): AudioBuffer;
446
+ }
447
+
448
+ /**
449
+ * Realtime time-stretch via AudioWorklet.
450
+ *
451
+ * The companion to the offline `StretchProcessor`. Loads a worklet processor
452
+ * into the AudioContext and exposes a node whose `stretch` AudioParam can be
453
+ * automated live — boss intros that bend in real time, slow-mo stings, etc.
454
+ *
455
+ * The worklet uses a phase-vocoder-lite ring buffer + linear-interp resampler
456
+ * paired with a small 1024-sample OLA grain to keep transients crisp. It's
457
+ * not as good as a dedicated SOLA pass for offline rendering, but it sounds
458
+ * fine for live ramps in the 0.5×–2× range.
459
+ */
460
+ interface StretchWorkletOptions {
461
+ /** Initial stretch factor. 1 = play at source rate. > 1 = faster. */
462
+ stretchFactor?: number;
463
+ /** Grain size in samples. Default 1024. Larger = smoother but more latency. */
464
+ grainSize?: number;
465
+ }
466
+ interface StretchWorkletNode extends AudioNode {
467
+ /** Live stretch factor — automate via setValueAtTime, linearRampToValueAtTime, etc. */
468
+ readonly stretch: AudioParam;
469
+ /** Disconnect and release. */
470
+ dispose(): void;
471
+ }
472
+ /**
473
+ * Ensure the realtime stretch worklet is registered on `ctx`. Idempotent —
474
+ * the processor module is registered at most once per context.
475
+ */
476
+ declare function ensureStretchWorklet(ctx: AudioContext): Promise<void>;
477
+ /**
478
+ * Construct a realtime stretch node. Call after `ensureStretchWorklet(ctx)`.
479
+ */
480
+ declare function createStretchWorkletNode(ctx: AudioContext, options?: StretchWorkletOptions): StretchWorkletNode;
481
+
482
+ type ParameterCurve = FadeCurve;
483
+ type Subscriber = (value: number) => void;
484
+ /**
485
+ * A named float you can drive at runtime. Set it from anywhere; subscribers
486
+ * (bus levels, FX wet, voice gain) update immediately.
487
+ *
488
+ * Bind a target to a parameter with `bindTo` — when the parameter changes,
489
+ * the curve maps [0..1] to a target range and applies the value. Repeated
490
+ * `set` calls override each other (no queue), making parameters ideal for
491
+ * "intensity"/"distance"/"tension" knobs that change continuously.
492
+ */
493
+ declare class Parameter {
494
+ readonly name: string;
495
+ private _value;
496
+ private subs;
497
+ constructor(name: string, initial: number);
498
+ get value(): number;
499
+ set(v: number): void;
500
+ subscribe(fn: Subscriber): () => void;
501
+ /**
502
+ * Bind a setter to this parameter. The parameter's [0..1] value (clamped)
503
+ * is mapped to [from..to] via `curve`, then the setter is called with the
504
+ * mapped value. Returns an unbind function.
505
+ */
506
+ bindTo(setter: (mapped: number) => void, opts?: {
507
+ from?: number;
508
+ to?: number;
509
+ curve?: ParameterCurve;
510
+ }): () => void;
511
+ }
512
+
513
+ type EngineState = 'cold' | 'unlocking' | 'live' | 'closed';
514
+
515
+ interface SoundDeps {
516
+ ctx: AudioContext;
517
+ buffer: AudioBuffer;
518
+ defaultBus: string;
519
+ resolveBusInput: (name: string) => AudioNode;
520
+ resolveSpatializer?: (busName: string, options: PlayOptions['spatializer']) => Spatializer | undefined;
521
+ trackVoice: (v: Voice, bus: string) => void;
522
+ releaseVoice: (v: Voice, bus: string) => void;
523
+ applyConcurrency?: (v: Voice, bus: string) => boolean;
524
+ }
525
+ /**
526
+ * A loaded sample — owns one decoded AudioBuffer, spawns Voices on play().
527
+ *
528
+ * Sound is created via engine.loadSound() / bank load; constructor is
529
+ * package-private.
530
+ */
531
+ declare class Sound {
532
+ readonly name: string;
533
+ private deps;
534
+ constructor(name: string, deps: SoundDeps);
535
+ get duration(): number;
536
+ play(options?: PlayOptions): Voice;
537
+ }
538
+
539
+ interface SpriteRegion {
540
+ /** Start offset within the buffer, in seconds. */
541
+ start: number;
542
+ /** Region duration in seconds. */
543
+ duration: number;
544
+ /** If true, looping plays this region back-to-back. Default false. */
545
+ loop?: boolean;
546
+ }
547
+ interface SpriteMap {
548
+ [name: string]: SpriteRegion;
549
+ }
550
+ /**
551
+ * One buffer, many named regions, one fetch.
552
+ *
553
+ * Use for cascades, UI variants, low-latency one-shots — anything where the
554
+ * cost of N separate decodes outweighs the cost of N region offsets into a
555
+ * single buffer. Built on top of an underlying Sound (the buffer); regions
556
+ * are cooperative — overlapping regions just produce overlapping voices.
557
+ */
558
+ declare class Sprite {
559
+ readonly name: string;
560
+ private regions;
561
+ private sound;
562
+ constructor(name: string, sound: Sound, regions: SpriteMap);
563
+ /** Region names defined on this sprite. */
564
+ list(): readonly string[];
565
+ has(region: string): boolean;
566
+ region(name: string): SpriteRegion;
567
+ /**
568
+ * Spawn a Voice playing the named region. The voice stops itself after
569
+ * `region.duration` seconds via an internal scheduleAt — the underlying
570
+ * AudioBufferSourceNode is one big buffer, so we can't rely on its
571
+ * natural-end event for region timing.
572
+ */
573
+ play(region: string, options?: SpriteRegionPlayOptions): Voice;
574
+ }
575
+ type SpriteRegionPlayOptions = Omit<PlayOptions, 'loop'> & {
576
+ loop?: boolean;
577
+ };
578
+
579
+ /**
580
+ * Stream a long media file through HTMLAudioElement → MediaElementAudioSource.
581
+ *
582
+ * Use for music tracks > 30s where decoding the whole file into RAM (the
583
+ * loadSound path) would waste memory and stall on iOS. The element handles
584
+ * progressive download and seek; we just route its output into the engine's
585
+ * bus graph so it picks up the same FX/sidechain as buffer-based voices.
586
+ *
587
+ * Created lazily — the underlying MediaElementAudioSource is only built on
588
+ * first play(), since it can't be reattached to a different bus once created.
589
+ */
590
+ declare class StreamSound {
591
+ readonly name: string;
592
+ private ctx;
593
+ private url;
594
+ private destination;
595
+ private el;
596
+ private node;
597
+ private gain;
598
+ private disposed;
599
+ constructor(name: string, ctx: AudioContext, url: string, destination: AudioNode);
600
+ /** Lazily construct the <audio> element + media-element source on first use. */
601
+ private ensure;
602
+ play(options?: {
603
+ volume?: number;
604
+ loop?: boolean;
605
+ }): Promise<void>;
606
+ pause(): void;
607
+ stop(): void;
608
+ seek(seconds: number): void;
609
+ get currentTime(): number;
610
+ get duration(): number;
611
+ get paused(): boolean;
612
+ setVolume(v: number): void;
613
+ fade(opts: FadeOptions): Promise<void>;
614
+ dispose(): void;
615
+ }
616
+
617
+ interface SnapshotState {
618
+ buses: Record<string, {
619
+ level: number;
620
+ muted: boolean;
621
+ }>;
622
+ parameters: Record<string, number>;
623
+ }
624
+ interface ApplyOptions {
625
+ /** Crossfade duration in milliseconds. Default 0 (snap). */
626
+ fadeMs?: number;
627
+ }
628
+ /**
629
+ * A captured mix-state preset. Capture it once with the engine in a known
630
+ * good state ("menu mood"), then `apply({ fadeMs: 250 })` to crossfade the
631
+ * entire mix back to that snapshot — bus levels, mutes, parameter values,
632
+ * everything in one call.
633
+ *
634
+ * Snapshots are immutable; mutate the engine and re-capture if you need a
635
+ * new one.
636
+ */
637
+ declare class Snapshot {
638
+ readonly name: string;
639
+ readonly state: SnapshotState;
640
+ private getBus;
641
+ private getParam;
642
+ constructor(name: string, state: SnapshotState, getBus: (name: string) => Bus | undefined, getParam: (name: string) => Parameter | undefined);
643
+ apply(opts?: ApplyOptions): Promise<void>;
644
+ }
645
+
646
+ interface Engine {
647
+ readonly state: EngineState;
648
+ readonly now: number;
649
+ /** Live AudioContext. Constructs one on first read. Throws if engine is closed. */
650
+ readonly context: AudioContext;
651
+ unlock(): Promise<void>;
652
+ close(): Promise<void>;
653
+ /**
654
+ * Load and decode an audio asset.
655
+ *
656
+ * Pass an array of URLs to ship a codec ladder — e.g. ['coin.webm', 'coin.m4a'].
657
+ * The first URL the browser can decode wins; this is how you serve Opus to
658
+ * everyone except older iOS Safari without bloating the bundle.
659
+ */
660
+ loadSound(name: string, url: string | readonly string[], options?: LoadSoundOptions): Promise<Sound>;
661
+ /** Register a Sound from an AudioBuffer you constructed yourself (procedural, custom-decoded, time-stretched). */
662
+ createSound(name: string, buffer: AudioBuffer, options?: {
663
+ bus?: string;
664
+ }): Sound;
665
+ /** Drop a sound from the registry. Active voices keep playing until they end naturally. */
666
+ removeSound(name: string): void;
667
+ hasSound(name: string): boolean;
668
+ /**
669
+ * Load a single buffer with a region map; spawn region-bound voices via
670
+ * `engine.sprite('cascade').play('match-3', ...)`.
671
+ */
672
+ loadSprite(name: string, url: string | readonly string[], regions: SpriteMap, options?: LoadSoundOptions): Promise<Sprite>;
673
+ /** Look up a previously loaded sprite. Throws SoundNotFoundError on miss. */
674
+ sprite(name: string): Sprite;
675
+ /** True if `name` was loaded as a sprite. */
676
+ hasSprite(name: string): boolean;
677
+ /**
678
+ * Stream a long media file via HTMLAudioElement + MediaElementAudioSource.
679
+ * Use for music tracks > 30s — avoids decoding the whole file into RAM,
680
+ * and is the only safe path on iOS for multi-minute assets.
681
+ */
682
+ loadStream(name: string, url: string | readonly string[], options?: LoadSoundOptions): StreamSound;
683
+ /** Look up a registered stream. */
684
+ stream(name: string): StreamSound;
685
+ hasStream(name: string): boolean;
686
+ sound(name: string): Sound;
687
+ bus(name: string): Bus;
688
+ /**
689
+ * Crossfade helper. Stops `from` over `ms` while playing `to` over the same
690
+ * window with `equal-power` curves so the perceived loudness stays flat.
691
+ *
692
+ * Returns the new Voice. If `to` is already playing, its level is faded up
693
+ * from 0 instead of starting fresh.
694
+ */
695
+ crossfade(from: string, to: string, options?: CrossfadeOptions): Voice;
696
+ scheduleAt(audioTime: number, fn: () => void): () => void;
697
+ /** All currently active voices (across all buses). */
698
+ activeVoices(): readonly Voice[];
699
+ onStateChange(fn: (s: EngineState) => void): () => void;
700
+ /** Get or create a named Parameter. */
701
+ parameter(name: string, initial?: number): Parameter;
702
+ /** Capture the current mix state into a named Snapshot. */
703
+ captureSnapshot(name: string): Snapshot;
704
+ /** Build a Snapshot from explicit state without capturing the live engine. */
705
+ snapshot(name: string, state: SnapshotState): Snapshot;
706
+ }
707
+ interface CrossfadeOptions {
708
+ /** Crossfade duration in ms. Default 1500. */
709
+ ms?: number;
710
+ /** Bus to play `to` on (and to look up `from` on). Defaults to the sound's defaults. */
711
+ bus?: string;
712
+ /** Loop the new voice. Default true (music swap is the canonical use case). */
713
+ loop?: boolean;
714
+ /** Curve. Default 'equal-power' so the sum stays at constant power. */
715
+ curve?: 'linear' | 'equal-power';
716
+ /** Override target volume of the incoming voice (0..1). Default 1. */
717
+ toVolume?: number;
718
+ }
719
+ /**
720
+ * Construct a new engine. Does NOT touch the AudioContext — that happens on
721
+ * the first unlock() or play() call. Safe to call before any user gesture.
722
+ */
723
+ declare function createEngine(config?: EngineConfig): Engine;
724
+
725
+ /**
726
+ * The Master stage. Headroom-aware gain into an optional brick-wall limiter,
727
+ * then to destination. Buses connect their output to master.input.
728
+ *
729
+ * Headroom is a static gain offset; the limiter is a fast-attack
730
+ * DynamicsCompressorNode that catches peaks the headroom can't tame when
731
+ * heavy FX stack on top of busy mixes.
732
+ */
733
+ declare class Master {
734
+ readonly input: GainNode;
735
+ private headroomDb;
736
+ private ctx;
737
+ private limiterNode;
738
+ private limiterCfg;
739
+ private destination;
740
+ constructor(ctx: AudioContext, config?: MasterConfig);
741
+ setHeadroom(db: number): void;
742
+ get headroom(): number;
743
+ /**
744
+ * Enable or update the master limiter. Pass `null` to disable.
745
+ * The limiter sits between master gain and destination.
746
+ */
747
+ setLimiter(cfg: MasterLimiterConfig | null): void;
748
+ /** Live gain reduction in dB. 0 if no limiter is engaged. */
749
+ get reduction(): number;
750
+ dispose(): void;
751
+ private rewire;
752
+ }
753
+
754
+ /**
755
+ * Codec capability + asset-source picking.
756
+ *
757
+ * Recommended encoding pipeline:
758
+ * - Primary: WebM/Opus — smallest, best quality/byte, supported in
759
+ * Chrome, Firefox, Edge, and Safari 14.1+ on macOS / iOS 17+.
760
+ * - Fallback: AAC in M4A — required for older iOS Safari (≤16) and
761
+ * older macOS Safari without Opus support.
762
+ *
763
+ * Ship both; pickSource() returns the first URL the browser can decode.
764
+ *
765
+ * canPlay() uses HTMLAudioElement.canPlayType — it gives a sound (no pun
766
+ * intended) prediction without actually fetching anything. The Web Audio
767
+ * decoder will accept anything HTMLAudioElement says it can play, plus
768
+ * a few extras (uncompressed WAV always works), so canPlay is conservative.
769
+ */
770
+ type AudioMimeType = 'audio/webm; codecs="opus"' | 'audio/ogg; codecs="opus"' | 'audio/ogg; codecs="vorbis"' | 'audio/mp4; codecs="mp4a.40.2"' | 'audio/mpeg' | 'audio/wav' | 'audio/flac';
771
+ declare function canPlay(mime: AudioMimeType): boolean;
772
+ declare function mimeForUrl(url: string): AudioMimeType | null;
773
+ /**
774
+ * Given a list of URLs (e.g. ['sfx.webm', 'sfx.m4a']), return the first one
775
+ * the browser claims it can play. If none match — or there's no DOM, e.g.
776
+ * during SSR — return the first URL and let decodeAudioData decide.
777
+ */
778
+ declare function pickSource(urls: readonly string[]): string;
779
+
780
+ /**
781
+ * RMS-based loudness normalization on a decoded AudioBuffer.
782
+ *
783
+ * `engine.loadSound(..., { normalize: true })` runs this at decode-time
784
+ * and produces a buffer pre-scaled so all sounds sit at the same perceived
785
+ * loudness — removing a workflow tax that game-audio teams currently pay
786
+ * in their DAW. Pass an object to override the target RMS or peak ceiling.
787
+ */
788
+ interface LoudnessOptions {
789
+ /** Target RMS (linear, 0..1). Default 0.1 (~ -20 dBFS). */
790
+ targetRms?: number;
791
+ /** Hard ceiling for the resulting peak; gain is reduced if it would clip. Default 0.99. */
792
+ peakCeiling?: number;
793
+ }
794
+ type NormalizeFlag = boolean | LoudnessOptions;
795
+ declare function applyLoudnessNormalization(buffer: AudioBuffer, flag: NormalizeFlag): AudioBuffer;
796
+ declare function computeNormalizationGain(buffer: AudioBuffer, opts: Required<LoudnessOptions>): number;
797
+
798
+ export { type ApplyOptions, type AudioMimeType, BankNotLoadedError, Bus, type BusConfig, BusNotFoundError, Compressor, type CompressorConfig, type ConcurrencyConfig, type CrossfadeOptions, 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, Reverb, type ReverbConfig, type SidechainConfig, Snapshot, type SnapshotState, Sound, SoundNotFoundError, type SpatialOptions, Spatializer, Sprite, type SpriteMap, type SpriteRegion, type SpriteRegionPlayOptions, StreamSound, StretchProcessor, type StretchWorkletNode, type StretchWorkletOptions, Voice, type VoiceJitter, ZvukError, applyLoudnessNormalization, canPlay, computeNormalizationGain, createEngine, createStretchWorkletNode, ensureStretchWorklet, mimeForUrl, pickSource };