import { Howl } from 'howler'; /** * Configuration for {@link createAudio}. * * @public */ interface AudioOptions { /** * If true (default), the first user gesture (touchend / pointerup / * keydown) on the page calls `Howler.ctx.resume()` and detaches the * listeners once the context is actually running. Set false if you want * to wire the unlock manually via {@link Audio.unlock}. */ autoUnlock?: boolean; /** * Master volume. Range `[0, 1]`. Default `1`. Applied via Howler's * GLOBAL `Howler.volume()`, not scoped to this Audio instance — other * `Audio` instances (or callers) that also touch `Howler.volume()` share * and can overwrite it. Prefer one `Audio` controller per app/scene. */ volume?: number; /** * Re-attempt `Howler.ctx.resume()` when the page visibility flips back * to visible. Best-effort iOS Safari workaround for the "context * suspends after background" pattern. Default `true`. */ resumeOnVisibility?: boolean; } /** * Per-`play()` options. * * @public */ interface PlayOptions { /** * Relative `[0, 1]` per-voice volume. Default `1`. This is multiplied by * the Audio instance's master volume (applied globally by Howler), not * defaulted to it — defaulting to the master would double-attenuate. */ volume?: number; /** * Playback rate. Default `1`. Must be a finite number: a non-finite rate * throws {@link AudioError} before any voice starts. */ rate?: number; /** Loop the buffer. Default `false`. */ loop?: boolean; /** * Aborting this signal calls `stop()` on the returned sound id and * unhooks any internal listeners. */ signal?: AbortSignal; } /** * Fade curve for {@link CrossfadeOptions.curve}. * * - `'linear'` — amplitude ramp via Howler fade() (default; backward-compat). * - `'equal-power'` — perceptual-loudness-preserving sin/cos ramp scheduled * directly on each sound's Web Audio GainNode * (`_node.gain`) as piecewise `linearRampToValueAtTime` * points. Requires Howler to be in Web Audio mode; in HTML5 * fallback mode it throws `AudioError` and the caller may * downgrade to linear. * * @public */ type CrossfadeCurve = "linear" | "equal-power"; /** * Options for {@link Audio.crossfade}. * * @public */ interface CrossfadeOptions { /** * Crossfade duration in seconds. Must be a finite number `> 0`. The * completion timer is clamped to 2,147,483,647 ms (about 24.8 days). */ duration: number; /** * Aborting resolves the promise immediately. On the `'equal-power'` * curve, aborting also freezes both ramps at their current gain. On the * `'linear'` curve (Howler's own `fade()`), Howler's fades cannot be * cancelled mid-flight, so aborting does NOT stop the in-progress ramps — * it only makes the returned promise settle early. Neither curve stops * `from` on abort: after an abort the caller owns both voices; stop or * re-fade `from` yourself. */ signal?: AbortSignal; /** * Start the incoming voice looping. Default `false`. The flag is applied to * the voice this call starts (Howler's per-id `loop(id)`), so it matches * the caller's intent even if the Howl-level loop flag differs. */ loop?: boolean; /** * Fade curve. Default `'linear'` (backward-compat). * See {@link CrossfadeCurve}. * * @remarks * `'equal-power'` schedules relative `[0, 1]` sin/cos ramps directly on each * sound's Web Audio GainNode (`_node.gain`) as 64-point piecewise * `linearRampToValueAtTime` schedules (not `setValueCurveAtTime`, whose * exclusive time window makes any other gain write during the ramp — e.g. * Howler's own volume / fade / resume — throw `NotSupportedError`): the * outgoing sound follows `cos` (1 -> 0) and the incoming sound follows `sin` * (0 -> 1), so `sin^2 + cos^2 = 1` keeps the perceived loudness flat. The * curves are NOT scaled by the master volume — the master is applied exactly * once via Howler's global gain, so scaling here as well would attenuate the * crossfade to mv². No extra GainNodes are inserted, so there is no re-routing * to restore. AbortSignal cancellation calls `cancelScheduledValues(now)` then * `setValueAtTime(currentValue, now)` on every scheduled gain (in that order) * and resolves early (not rejecting). * * `from` is assumed to be already playing; only `to` is started by the call. * On normal completion the ramped `from` voices are stopped, as on the * `'linear'` curve. Requires Web Audio mode — throws `AudioError` under the * HTML5 fallback. `Howl.fade()` is NOT invoked in this path. */ curve?: CrossfadeCurve; } /** * Handle to a loaded audio buffer. One handle backs N concurrent plays; * Howler returns a numeric sound id per `play()` call so individual * instances can be paused / stopped / faded. * * @public */ interface Sound { /** Start playback. Returns Howler's sound id for this instance. */ play(opts?: PlayOptions): number; /** Pause one instance, or all instances if id is omitted. */ pause(id?: number): void; /** Stop one instance, or all instances if id is omitted. */ stop(id?: number): void; /** * Resume a paused instance, or all paused instances if id is omitted. * * - With `id`: resumes that specific voice and returns it, or returns * `-1` if `id` is not currently a paused, non-ended voice (e.g. it * already ended naturally, was never paused, or its `play()` is still * queued behind the AudioContext). * - Without `id`: resumes every currently-paused, non-ended voice * (`_paused === true && _ended !== true`) and returns the last resumed * id, or `-1` if nothing was resumed. * * @throws {@link AudioDisposedError} if called after {@link dispose}. */ resume(id?: number): number; /** * Linearly fade from `from` to `to` over `ms` milliseconds. Resolves * after `ms` regardless of whether the fade visibly completed (Howler * fades cannot be cancelled mid-flight). * * Never throws synchronously; every failure is a rejection, checked in this * order before `Howl.fade()` runs (so a rejected call has no side effect): * {@link AudioDisposedError} if `dispose()` was already called; * {@link AudioError} if `from` or `to` is not a finite number in `[0, 1]`; * {@link AudioError} if `ms` is not a finite number `>= 0`. Delays above * 2,147,483,647 ms (about 24.8 days) are clamped. If `dispose()` is called * AFTER `fade()` started, the underlying howl is unloaded but the promise * still resolves at the scheduled time. */ fade(from: number, to: number, ms: number, id?: number): Promise; /** * Idempotent teardown for this Sound only. Stops every instance, * unloads the buffer, releases the Howl. Subsequent `play` / `pause` / * `stop` / `resume` throw {@link AudioDisposedError} synchronously; * `fade` instead returns a promise that rejects with it. */ dispose(): void; /** * Escape hatch — direct access to the underlying Howl for advanced API * not surfaced by aiaudiojs (e.g. sprites, custom HTML5 element). */ readonly nativeHowl: Howl; /** `true` once {@link dispose} has been called. */ readonly disposed: boolean; } /** * Top-level audio orchestrator. One per page (or per game). Wraps Howler's * global `AudioContext` and provides ai\*js-style lifecycle. * * @public */ interface Audio { /** * Resume the underlying AudioContext. Safe to call before any user * gesture (will no-op until the gesture arrives). Idempotent. */ unlock(): Promise; /** * Load a buffer. Resolves to a {@link Sound} once Howler's `onload` * fires; rejects with {@link AudioError} on load failure or with the * standard `AbortError` if `signal` aborts mid-load. * * @remarks * **F3 — abort racing decode completion:** If `signal` aborts while a load is * in flight, `load()` rejects with `AbortError` and unloads the Howl. The * first of Howler's `load` / `loaderror` events or the abort to fire settles * the promise and detaches the other two listeners (a `settled` guard plus * bare `off()`), so a `load` event Howler still emits *after* the abort has * already rejected is a no-op: no `Sound` is added to the internal set and * no second `unload()` happens. `dispose()` / `disposeAll()` settle every * in-flight `load()` the same way, immediately: it rejects with * {@link AudioDisposedError} and its Howl is unloaded, without waiting for * Howler's decode to finish. * * @security The `url` parameter is passed directly to `new Howl({ src: [url] })`, * which forwards it to `Audio.src` (HTML5 mode) or `XMLHttpRequest.open` * (Web Audio decode). Any URL the caller passes is trusted. If you accept * URLs from untrusted sources you MUST validate them before calling `load`. */ load(url: string, signal?: AbortSignal): Promise; /** * Crossfade between two loaded sounds over `opts.duration` seconds. * * @remarks * Default `'linear'` curve delegates to `Howl.fade()`: every voice of `from` * ramps 1 -> 0 and the one voice this call starts on `to` ramps 0 -> 1. * Aborting via `opts.signal` clears the resolve timer but cannot stop the * in-flight Howler ramp (both continue silently). Opt-in * `curve: 'equal-power'` (0.3.0) schedules sin/cos ramps on the AudioContext * as piecewise `linearRampToValueAtTime` points, preserving perceptual * loudness; abort cancels the schedule cleanly. * * **Completion.** Both curves capture `from`'s playing voices before `to` * starts. When the duration elapses, those voices are stopped (unless `from` * was disposed meanwhile), so a looping outgoing track does not keep playing * silently. `crossfade(s, s)` is supported: the old voices of `s` stop and * the new one keeps playing. On abort neither curve stops `from`: the caller * owns both voices; stop or re-fade `from` yourself. `opts.loop` starts the * incoming voice looping. * * **Failure channels — synchronous `throw` vs promise rejection.** This method * reports errors on two different channels; a `.catch()` alone does NOT cover * both, so wrap the call in `try { await audio.crossfade(...) } catch` to catch * everything: * - **Synchronously thrown (before a promise exists):** * `AudioDisposedError` when the Audio instance is disposed; * `AudioError` when `from` or `to` is a disposed Sound (or not a Sound); * `AudioError` when Howler's private `_sounds` internal is unavailable * (unexpected Howler version); and, on the `equal-power` path only, * `AudioError` when Howler is in HTML5 fallback mode (no Web Audio context / * no `_node.gain`) or the AudioContext is not running. `from`'s voices are * read before `to` starts; if `to` has already started when a check fails, * its voice is stopped before the throw, so no silent orphan is left. * - **Rejected (a returned promise):** `AudioError` when `opts` is missing or * `opts.duration` is not a finite number `> 0`; `DOMException("AbortError")` * when `opts.signal` is already aborted at call time. Both of these are * checked before any voice is started, so a rejection never orphans a voice. * * **F2 — concurrent crossfades on the same Sound:** Once a new `crossfade()` * starts on a `Sound`, any `AbortController` that was issued for a *previous* * crossfade on that same Sound **must not be fired** after the new crossfade * begins. Aborting the old controller would call `cancelScheduledValues` and * `setValueAtTime` on the GainNode, overwriting the ramp the new crossfade just * scheduled. Each crossfade owns its abort signal exclusively; the caller is * responsible for retiring old controllers before starting a new crossfade. * * **F5 — equal-power gain is relative `[0, 1]`:** The equal-power ramps are * scheduled as relative gain values (`from` follows `cos`: 1 → 0; `to` follows * `sin`: 0 → 1); the master volume is applied exactly once via Howler's global * gain, not folded into these curves. The `cos` ramp therefore starts the * outgoing voice at relative gain `1`, regardless of any per-instance volume it * was played with — so if `from` was started with `from.play({ volume: 0.5 })`, * its gain snaps to relative `1` at the start of the crossfade, which may * produce an audible click. For a click-free transition, ensure `from` is * playing at its full relative gain before calling * `crossfade({ curve: 'equal-power' })`. * * **F9 — AudioParam scheduling throwing mid-crossfade:** If a * `linearRampToValueAtTime` / `setValueAtTime` call throws *after* the ramps have begun (e.g. the context * is closed unexpectedly mid-crossfade), the `to` sound may be left running at * its scheduled gain with no further ramp applied. This is a known defensive * edge case distinct from the pre-flight `AudioError` throws above: it surfaces * as the raw Web Audio exception, and callers that need to recover should catch * it and call `to.stop()` explicitly. (The pre-flight HTML5-fallback / disposed * / reshaped-`_sounds` throws, by contrast, never leave a `to` voice running.) * * On normal completion both curves stop the `from` voices by the ids captured * before `to` started; a `from` voice started after the call (including one * Howler recycled into an ended voice's pool slot) is left playing. * * The completion timer is clamped to 2,147,483,647 ms (about 24.8 days). */ crossfade(from: Sound, to: Sound, opts: CrossfadeOptions): Promise; /** * Master volume. Getting/setting this reads/writes Howler's GLOBAL * `Howler.volume()` — it does not iterate or scope to this Audio * instance's own Sounds, so it also affects any other `Audio` instance * or direct Howler usage sharing the page. */ volume: number; /** * Idempotent teardown. Alias for {@link Audio.disposeAll}, provided so * the Audio interface conforms to the ai*js convention that every * factory-built handle exposes `dispose()`. Tears down every * {@link Sound} this Audio instance created, rejects every in-flight * `load()` with {@link AudioDisposedError}, and releases the * underlying Howler bindings. Subsequent `crossfade` throws * {@link AudioDisposedError} synchronously; `load` and `unlock` instead * return a promise that rejects with it. */ dispose(): void; /** * Idempotent teardown — identical effect to {@link Audio.dispose}; * kept as a descriptive name for code paths that want to be explicit * about the cascading nature (every Sound this Audio created is torn * down). Subsequent `crossfade` throws {@link AudioDisposedError} * synchronously; `load` and `unlock` instead return a promise that * rejects with it. */ disposeAll(): void; /** `true` once {@link disposeAll} has been called. */ readonly disposed: boolean; } /** * Recoverable audio error. Thrown on load failure, on unsupported * codec, and on precondition violations. * * @public */ declare class AudioError extends Error { readonly name = "AudioError"; } /** * Thrown by any method called after {@link Audio.disposeAll} (on the Audio * instance) or after {@link Sound.dispose} (on a specific Sound). * * @public */ declare class AudioDisposedError extends Error { readonly name = "AudioDisposedError"; } /** * Construct an Audio instance backed by Howler.js. * * Requires `howler@^2.2.4` as a peer dependency. * * @example * ```ts * import { createAudio } from "aiaudiojs"; * * const audio = createAudio({ autoUnlock: true }); * * const sfx = await audio.load("zap.mp3"); * const id = sfx.play({ volume: 0.8 }); * * const bgmA = await audio.load("level1.mp3"); * const bgmB = await audio.load("level2.mp3"); * bgmA.play({ loop: true }); * * // Switch tracks with a 2-second crossfade. * await audio.crossfade(bgmA, bgmB, { duration: 2 }); * * audio.disposeAll(); * ``` * * @public */ declare function createAudio(opts?: AudioOptions): Audio; export { type Audio, AudioDisposedError, AudioError, type AudioOptions, type CrossfadeCurve, type CrossfadeOptions, type PlayOptions, type Sound, createAudio };