cacophony
    Preparing search index...

    Class Playback

    The base interface for any sound-producing entity, including individual sounds, groups, and playbacks. BaseSound

    Hierarchy

    • BasePlayback
      • Playback

    Implements

    Index
    _effectChain?: EffectChain
    _fadeInConfig?: {
        duration: number;
        perLoop: boolean;
        targetVolume: number;
        type: FadeType;
    }
    _fadeOutConfig?: { duration: number; type: FadeType }
    _filters: BiquadFilterNode[] = []
    _isFading: boolean
    _loopEndCallback?: () => void
    _panType: PanType
    _sendGains: Map<Bus, GainNode> = ...

    Per-playback send-gain allocations owned by the shared routing state machine. Cleanup disconnects every allocation deterministically.

    _state: PlaybackState = "unplayed"
    currentLoop: number = 0
    eventEmitter: TypedEventEmitter<PlaybackEvents> = ...
    gainNode?: GainNode
    loopCount: LoopCount = 0
    origin: Sound
    panType: PanType
    position: Position

    Requested position target; initial poses are immediate, subsequent writes use spatialSmoothingTau.

    source?: SourceNode
    spatialSmoothingTau: number

    Spatial exponential time constant in seconds (default 0). Setting 0 snaps pending targets.

    • get _directOutput(): AudioNode
      Internal

      The direct path after the panner (no reflection images): what the voice's own direct sound sounds like, and the send source of a voice that is not HRTF-panned.

      Returns AudioNode

    • get _sendTap(): AudioNode
      Internal

      Aux sends carry the direct path only; reflection images are heard dry. An HRTF-panned voice sends its direct path from before the panner, so the send does not depend on the source's direction (wireSendFeed).

      Returns AudioNode

    • get _spatialSmoothingActive(): boolean
      Internal

      Smooth only while a voice can be heard or resumed. Unplayed and stopped voices take poses immediately, so a replayed voice starts at its requested pose.

      Returns boolean

    • get bandGains(): readonly number[]

      The last requested linear octave-band gains (see OCTAVE_BAND_CENTERS), initially all 1.

      Returns readonly number[]

    • get currentTime(): number

      Current source position in seconds. Playing HTML media reports its observed cursor, including buffering stalls and native loop wraps. Buffer playback follows the render clock; idle and paused voices retain their committed offset.

      Returns number

    • get duration(): number

      Gets the duration of the audio in seconds.

      Returns number

      The duration of the audio or NaN if the duration is unknown.

      Throws an error if the sound has been cleaned up.

    • get isFading(): boolean

      Returns boolean

    • get outputNode(): GainNode

      Gets the output node of this playback's audio graph: the full voice, the direct path summed with any early-reflection images, after volume and fades. This is the final node in the internal chain before connection to destination. Use this to manually wire the playback into custom audio graphs.

      Returns GainNode

      The unity gain node that serves as the output of this playback.

      Throws an error if the playback has been cleaned up.

      // Manual routing through custom effects
      const playback = sound.play()[0];
      playback.disconnect(); // Disconnect from default destination
      playback.connect(reverbNode).connect(context.destination);
    • get pannerDestination(): AudioNode

      The node the panner feeds; the volume node unless a subclass places volume earlier.

      Returns AudioNode

    • get playbackRate(): number

      Gets the current playback rate of the audio.

      Returns number

    • set playbackRate(rate: number): void

      Sets the playback rate immediately; equivalent to setPlaybackRate(rate, 0).

      Parameters

      • rate: number

      Returns void

      If the rate is not greater than 0.

    • set sourceLoop(loop: boolean): void

      Sets whether the audio source should loop.

      Parameters

      • loop: boolean

      Returns void

      Throws an error if the sound has been cleaned up.

    • get state(): PlaybackState

      Gets the current lifecycle state without changing playback.

      Returns PlaybackState

    • get stereoPan(): number | null

      Requested stereo pan target, including during smoothing.

      Returns number | null

    • set stereoPan(value: number): void

      Parameters

      • value: number

      Returns void

    • get supportsClipLoop(): boolean

      Whether this live voice can enforce native buffer clip boundaries. HTML media cannot.

      Returns boolean

    • Internal

      Snap pending spatial transitions to their requested targets.

      Returns void

    • Internal

      Preflight Sound broadcasts and play options before any mutation.

      Parameters

      Returns void

    • Internal

      Validate a spatial write without changing the voice.

      Parameters

      • options: SpatialOptions

      Returns void

    • Cancels any in-progress fade, emitting fadeCancel if a fade was active.

      Returns void

    • Cleans up resources used by the Playback instance. This method should be called when the audio is no longer needed to free up resources.

      Returns void

    • Creates a clone of the current Playback instance with optional overrides for certain properties. This method allows for the creation of a new Playback instance that shares the same audio context and source node but can have different settings such as loop count or pan type. The clone is connected to the origin Sound's primary route and registered with the Sound.

      Parameters

      • overrides: Partial<PlaybackCloneOverrides> = {}

      Returns Playback

      Throws an error if the sound has been cleaned up.

    • Configures a fade-out to be applied when the playback ends naturally (last loop iteration).

      Parameters

      • duration: number

        The fade-out duration in milliseconds.

      • Optionaltype: FadeType

        The fade curve type. Defaults to "linear".

      Returns void

    • Connects this playback's output to an AudioNode or AudioParam. Follows the Web Audio API connection pattern.

      Parameters

      Returns AudioNode

      The destination node (for chaining).

      Throws an error if the playback has been cleaned up.

      // Chain multiple effects
      playback.connect(delay).connect(reverb).connect(context.destination);
    • Disconnects this playback's output from a specific destination or from all destinations.

      Parameters

      • Optionaldestination: AudioParam | AudioNode

        Optional specific destination to disconnect from. If omitted, disconnects from all destinations.

      Returns void

      Throws an error if the playback has been cleaned up.

      // Disconnect from all
      playback.disconnect();
      // Disconnect from specific node
      playback.disconnect(reverbNode);
    • Type Parameters

      • K extends "seek" | (keyof BaseAudioEvents)

      Parameters

      Returns void

    • Type Parameters

      • K extends "seek" | (keyof BaseAudioEvents)

      Parameters

      Returns Promise<void>

    • Parameters

      • isResume: boolean

      Returns void

    • Fades in from silence to the current volume. Optionally stores config to re-trigger the fade on each loop iteration.

      Parameters

      • duration: number

        The fade duration in milliseconds.

      • Optionaltype: FadeType

        The fade curve type. Defaults to "linear".

      • Optionaloptions: { perLoop?: boolean; startTime?: number }

        Optional. Set perLoop: true to re-trigger fadeIn on each loop.

      Returns Promise<void>

      Resolves when the fade completes.

    • Fades the volume to a target value, emitting fadeStart and fadeEnd events.

      Parameters

      • value: number
      • duration: number
      • type: FadeType = "linear"
      • Optionaloptions: { startTime?: number; startValue?: number }

      Returns Promise<void>

    • Sets or gets the loop count for the audio.

      Parameters

      • OptionalloopCount: LoopCount

        The number of times the audio should loop. 'infinite' for endless looping.

      Returns LoopCount

      The loop count if no parameter is provided.

      Throws an error if the sound has been cleaned up or if the source type is unsupported.

    • Handles the loop event when the audio ends. This method is bound to the 'onended' event of the audio source. It manages looping logic and restarts playback if necessary.

      Returns void

    • Remove event listener.

      Type Parameters

      • K extends "seek" | (keyof BaseAudioEvents)

      Parameters

      Returns void

    • Register event listener.

      Type Parameters

      • K extends "seek" | (keyof BaseAudioEvents)

      Parameters

      Returns () => void

      Cleanup function

    • Silently prepares an idle or paused voice at a finite offset in seconds. Buffers resolve immediately. Media elements wait for metadata, a seekable range containing the target, and completed seeking with current audio data. No play(), context resume, or autoplay primer is performed. State is retained. A later preparation, play, seek, stop, or cleanup rejects pending work with AbortError. Cancellation does not roll back a browser seek already requested. Live/unknown-duration media rejects with NotSupportedError; readiness timeout rejects with TimeoutError. Browser media seeking is not sample accurate.

      Parameters

      Returns Promise<void>

    • Parameters

      • handle: AudioNode
      • paramName: string
      • value: number
      • Optionaloptions: { duration?: number; type?: FadeType }

      Returns void

    • Parameters

      Returns void

    • End this started buffer activation at an absolute AudioContext time. A deadline before a future onset prevents all onset audio. Past deadlines stop now. Rate changes do not move this render-clock deadline. A later call replaces it; pause, seek, source recreation, stop and cleanup revoke it. Downstream effect tails remain. Legacy numeric repeats and ended-time fade-outs cannot share this per-source deadline.

      Parameters

      • atAudioSeconds: number

      Returns void

    • Renders per-band attenuation for this voice (for example air absorption over the path, or transmission through an obstacle) independently of volume, fades, and positioning. The caller owns geometry, materials, and policy.

      gains holds one linear gain in [0, 1] per octave band of OCTAVE_BAND_CENTERS (125 Hz to 16 kHz). A broadband gain carries the common level and a cascade of a low shelf, six peaking filters and a high shelf shapes the rest, designed per call so the response at every band center is within 1 dB of the target wherever the target is above -30 dB; bands at or below -30 dB render at or below -30 dB. Below 125 Hz and above 16 kHz the response follows the end shelves rather than returning to unity. Bands whose filter frequency is at or above 0.45 times the sample rate are left flat (the 16 kHz band below a 17.8 kHz sample rate, for example).

      The stage sits after user effects and before the panner. Nodes are allocated on the first call with any gain other than 1 and reused, including after a return to all ones, which is transparent.

      Parameters

      • gains: readonly number[]

        Eight linear band gains in [0, 1].

      • durationMs: number = 50

        Linear transition duration in milliseconds, default 50; 0 applies immediately.

      Returns void

      For a wrong length, a gain outside [0, 1], or a negative/non-finite duration.

      If this playback has been cleaned up.

    • Wires effects -> volume -> [reflection fan-out] -> [band stage] -> output (the panner). Volume sits ahead of the fan-out so it applies to the direct path and every image while the direct path stays separable for sends; the band stage, delays and panners are linear, so the order does not change the steady-state sound.

      Parameters

      Returns void

    • Configure a hard clip end and native loop points, in Sound-relative seconds. Configure while idle or paused. loop(0) ends at R; loop("infinite") wraps R to L. Numeric repeats and per-loop fades are unsupported with explicit bounds.

      Parameters

      • startSeconds: number
      • endSeconds: number

      Returns void

    • Sets the pitch-shift factor for this playback, resurrecting the dormant phase-vocoder worklet (Jean Laroche & Mark Dolson, "New Phase-Vocoder Techniques for Pitch-Shifting, Harmonizing and Other Exotic Effects", 1999 IEEE WASPAA — peak-based pitch shift with Identity Phase-Locking).

      On first use (factor !== 1) the phase-vocoder AudioWorkletNode is built and added as an ordinary entry at the tail of the pre-panner effect chain: source → [filters] → phase vocoder → gainNode → panner → output. The factor is forwarded to the node's pitchFactor AudioParam (1 = no shift, 2 = +1 octave, 0.5 = -1 octave).

      Parameters

      • factor: number

        Pitch multiplier (> 0).

      Returns Promise<void>

      if the playback has been cleaned up or factor <= 0.

    • Changes the playback rate, ramping a decoded-buffer source's rate linearly from its current value over durationMs. Media-element sources cannot ramp and take the rate at once. The source position stays exact through a ramp: currentTime, pause and loop bookkeeping integrate the rate over time. playbackRate reports the requested (target) rate.

      Parameters

      • rate: number

        Target rate, greater than 0.

      • durationMs: number = 0

        Linear ramp duration in milliseconds, default 0 (immediate).

      Returns void

      If the rate is not greater than 0.

      For a negative or non-finite duration.

    • Adds early reflections: mirrored copies of this voice heard from other positions. Each image taps the voice after its effect chain and before its band stage and panner, then passes a delay, a band cascade (the same design as setBandGains, with gain as an extra broadband factor) and its own panner, and joins the voice's output, so volume and fades apply to it. Aux sends carry the voice's direct path only: images are heard dry at the output and never reach a send. The image panner only pans: it applies no distance attenuation (the caller's gain carries it). Image panners use the voice panner's panning model when the voice is HRTF-panned and equal-power panning otherwise, chosen when the stage is built.

      An update with the same image count ramps delays, positions and gains in place over durationMs; a different count rebuilds the images at their new values immediately; an empty array removes the stage.

      Parameters

      • images: readonly ReflectionImage[]

        Image positions (listener frame), delays in seconds after the direct signal (0..1), linear gains and eight band gains each.

      • durationMs: number = 50

        Linear transition duration in milliseconds, default 50; 0 applies immediately.

      Returns void

      For invalid image fields or a negative/non-finite duration.

      If this playback has been cleaned up or the context cannot create delay nodes.

    • Fades out then stops the playback.

      Parameters

      • duration: number

        The fade-out duration in milliseconds.

      • Optionaltype: FadeType

        The fade curve type. Defaults to "linear".

      Returns Promise<void>

      Resolves when the fade completes and playback is stopped.