Class Sound

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

Hierarchy

  • PlaybackContainer<typeof FilterManager, this> & FilterManager<this>
    • Sound

Implements

Constructors

Properties

_cacophony?: Cacophony
_filters: BiquadFilterNode[] = []
_holdings: SoundCleanupHoldings = ...
_pitchFactor: number = 1

Pitch-shift factor applied to every playback of this Sound (1 = no shift). Fanned out across live playbacks by setPitchShift and applied to future playbacks at preplay. Drives the phase-vocoder worklet (Laroche & Dolson 1999 peak-based pitch shift).

_playbackRate: number = 1
_playbackUnsubscribes: WeakMap<Playback, (() => void)[]> = ...

Per-playback unsubscribe functions for the listeners that Sound attaches to each playback in preplay. Tracked so the Sound→playback closure cycle (each listener captures this) can be broken explicitly when the playback ends, stops, or is cleaned up — not only when the playback's own eventEmitter is torn down. A WeakMap keeps the entry GC- tied to the playback identity.

_position: Position = ...
_routeTarget: null | Bus = null

Primary route target for this Sound. null means master (the default — preplay connects to globalGainNode which IS master.input). When a Bus is assigned via routeTo, future playbacks connect to bus.input instead, and live playbacks are rewired.

_sends: Map<Bus, number> = ...

Additional send edges established by routeTo(bus, sendGain). Keyed by target bus → send gain value. At preplay we allocate one GainNode per send per playback so each playback has its own send edges (a per-Sound shared sendGain would crash the second simultaneous playback because both gainNodes would connect into the same single sendGain, doubling the dry signal). The actual GainNode lifecycle is owned by each Playback in Playback._sendGains — iterable so cleanup can walk every send and call disconnect().

_stereoPan: number = 0
_threeDOptions: ThreeDOptions = ...

Canonical 3D-audio configuration storage. Always holds a fully-populated HRTF variant (ThreeDOptions with panType: "HRTF") so callers reading via the getter never see undefined fields. Setting the stereo variant replaces this with the stereo shape (no stale HRTF fields).

_unregisterToken: object = {}
_volume: number = 1
buffer?: AudioBuffer
context: BaseContext
eventEmitter: TypedEventEmitter<SoundEvents> = ...
globalGainNode: GainNode
loopCount: LoopCount = 0
panType: PanType = "HRTF"
playbacks: Playback[]
soundType: SoundType = "buffer"
url: string

Accessors

  • get duration(): number
  • Retrieves the duration of the sound in seconds. If the sound is based on an AudioBuffer, it returns the duration of the buffer. Otherwise, if the sound has not been played and is a MediaElementSource, it returns NaN, indicating that the duration is unknown or not applicable.

    Returns number

    The duration of the sound in seconds.

  • get isPlaying(): boolean
  • Returns a boolean indicating whether the object is currently playing. an object is playing if any of its playbacks are currently playing.

    Returns boolean

  • get position(): Position
  • Retrieves the current 3D spatial position of the sound in the audio context. The position is returned as an array of three values[x, y, z].

    Returns Position

  • set position(position): void
  • Sets the 3D spatial position of the sound in the audio context. The position is an array of three values[x, y, z]. This method updates the position of all active playbacks of the sound.

    Parameters

    Returns void

  • get stereoPan(): number
  • Returns number

  • set stereoPan(value): void
  • Parameters

    • value: number

    Returns void

  • get threeDOptions(): ThreeDOptions
  • Returns a fresh copy of the canonical 3D-audio configuration. The clone prevents callers from mutating the container's internal state via the returned reference (previously the raw _threeDOptions object leaked).

    Returns ThreeDOptions

  • set threeDOptions(options): void
  • Accepts either a full canonical ThreeDOptions value, or a partial HRTF-options override (legacy ergonomics). When a partial is provided the existing variant is merged in place — and if the existing variant is stereo, the partial is interpreted as a switch back to HRTF defaults plus the override (no stale stereo fields). When a full variant is provided with a different panType, the storage is replaced wholesale so stale fields from the previous variant cannot be observed via the getter.

    Parameters

    Returns void

  • get volume(): number
  • Returns number

  • set volume(volume): void
  • Parameters

    • volume: number

    Returns void

Methods

  • Parameters

    • bus: Bus
    • gainValue: number

    Returns void

  • Reroute this sound off bus onto target when bus is being drained (typically just before it is destroyed). A sound may be BOTH primary-routed to bus AND have a send to it — both edges move.

    Parameters

    Returns void

  • Returns the AudioNode that future playbacks should connect to as their primary target. Handles the master bus alias and the destroyed-bus fallback (which warns).

    Returns GainNode

  • Apply a new primary route. If a bus is passed and it's the master bus, collapse to null so the canonical "route to master" representation is always null (matches the default).

    Parameters

    Returns void

    Throws

    if bus is destroyed. Symmetric with _addSend's guard; a destroyed bus is an invalid mutation target. (Sounds already routed BEFORE the bus was destroyed still fall back to master at preplay via _resolveRouteTargetNode — that path is separate.)

  • Detaches the Sound-side listeners that were registered on a playback in preplay. Idempotent — safe to call on a playback whose subscriptions were already torn down. Breaks the Sound↔playback closure cycle described on the entries in _playbackUnsubscribes.

    Parameters

    Returns void

  • Adds a BiquadFilterNode to the container's filter chain. Filters are cloned when creating new playbacks - existing playbacks are not affected. Each playback gets independent filter instances for isolated processing.

    Parameters

    Returns void

  • Returns void

  • Clones the current Sound instance, creating a deep copy with the option to override specific properties. This method allows for the creation of a new, independent Sound instance based on the current one, with the flexibility to modify certain attributes through the overrides parameter. This is particularly useful for creating variations of a sound without affecting the original instance. The cloned instance includes all properties, playback settings, and filters of the original, unless explicitly overridden.

    Parameters

    • overrides: Partial<SoundCloneOverrides> = {}

      An object specifying properties to override in the cloned instance. This can include audio settings like volume, playback rate, and spatial positioning, as well as more complex configurations like 3D audio options and filter adjustments.

    Returns Sound

  • Type Parameters

    • K extends (keyof BaseAudioEvents) | "soundError" | "loopEnd" | "rateChange"

    Parameters

    Returns void

  • Type Parameters

    • K extends (keyof BaseAudioEvents) | "soundError" | "loopEnd" | "rateChange"

    Parameters

    Returns Promise<void>

  • Fades in all playbacks from silence to their current volume.

    Parameters

    • duration: number

      The fade duration in milliseconds.

    • Optional type: FadeType

      The fade curve type. Defaults to "linear".

    Returns Promise<void>

    Resolves when all fades complete.

  • Fades out all playbacks from their current volume to silence.

    Parameters

    • duration: number

      The fade duration in milliseconds.

    • Optional type: FadeType

      The fade curve type. Defaults to "linear".

    Returns Promise<void>

    Resolves when all fades complete.

  • Fades the volume of all playbacks to a target value over a duration.

    Parameters

    • value: number

      The target volume (0 to 1).

    • duration: number

      The fade duration in milliseconds.

    • Optional type: FadeType

      The fade curve type. Defaults to "linear".

    Returns Promise<void>

    Resolves when all fades complete.

  • Sets or retrieves the loop behavior for the sound. If loopCount is provided, the sound will loop the specified number of times. If loopCount is 'infinite', the sound will loop indefinitely until stopped. If no argument is provided, the method returns the current loop count setting.

    Parameters

    • Optional loopCount: LoopCount

      The number of times to loop or 'infinite' for indefinite looping.

    Returns LoopCount

    The current loop count setting if no argument is provided.

  • Remove event listener.

    Type Parameters

    • K extends (keyof BaseAudioEvents) | "soundError" | "loopEnd" | "rateChange"

    Parameters

    • event: K
    • listener: ((data) => void)

    Returns void

  • Register event listener.

    Type Parameters

    • K extends (keyof BaseAudioEvents) | "soundError" | "loopEnd" | "rateChange"

    Parameters

    • event: K
    • listener: ((data) => void)

    Returns (() => void)

    Cleanup function

      • (): void
      • Returns void

  • Generates a Playback instance for the sound without starting playback. This allows for pre-configuration of playback properties such as volume and position before the sound is actually played.

    Returns Playback[]

  • Removes a BiquadFilterNode from the container's filter chain. Only affects future playbacks - existing playbacks retain their cloned filters.

    Parameters

    Returns void

    Throws

    If the filter was never added to this container.

  • Parameters

    Returns void

  • Routes this Sound to a Bus (or back to master). Two modes:

    • routeTo(target) — replace primary routing. Live playbacks are rewired: each playback's outputNode is disconnected from its current target and re-connected to the new target's input. Future playbacks read the stored target at preplay.
    • routeTo(target, sendGain) — ADD a send (does not change primary routing). An additional edge is created from each live playback through an allocated GainNode set to sendGain. Future playbacks get the same send at preplay.

    target may be a Bus instance or the name of a registered bus (string lookup via cacophony.getBus). A string with no matching bus throws.

    Passing the master bus (or cacophony.master) as target (no sendGain) is the canonical way to reset primary routing back to master.

    Parameters

    • target: string | Bus
    • Optional sendGain: number

    Returns void

  • Seeks to a specific time within the sound's playback.

    Parameters

    • time: number

      The time in seconds to seek to. This method iterates through all active Playback instances and calls their seek() method with the specified time.

    Returns void

  • Pitch-shifts every live playback of this Sound, resurrecting the dormant phase-vocoder worklet (Jean Laroche & Mark Dolson, 1999 IEEE WASPAA — peak-based pitch shift with Identity Phase-Locking). Mirrors how playbackRate fans a per-playback control out across this.playbacks. The factor is also stored so future playbacks pick it up at preplay.

    Parameters

    • factor: number

      Pitch multiplier (> 0; 2 = +1 octave, 0.5 = -1 octave).

    Returns Promise<void>

    Resolves once every live playback's worklet node has been built and its pitchFactor param updated.

  • Fades out all playbacks then stops them.

    Parameters

    • duration: number

      The fade-out duration in milliseconds.

    • Optional type: FadeType

      The fade curve type. Defaults to "linear".

    Returns Promise<void>

    Resolves when the fade completes and all playbacks are stopped.

  • OFFLINE independent time-stretch: produce a NEW buffer-based Sound whose tempo is changed by factor WITHOUT changing pitch (Phase Gradient Heap Integration, Průša & Holighaus, "Phase Vocoder Done Right", EUSIPCO 2017 / arXiv:2202.07382). factor > 1 is slower/longer, factor < 1 is faster/shorter. Only valid for buffer-based sounds (a loaded AudioBuffer); streaming / media-element sounds have no decoded buffer to transform.

    The original Sound is left untouched; a fresh Sound wrapping the stretched buffer is returned. Delegates to Cacophony.timeStretchBuffer.

    Parameters

    • factor: number

      Stretch factor (> 0); pitch is preserved.

    • Optional options: TimeStretchOptions

      Optional PGHI parameters (fftSize, analysisHop, tol, seed).

    Returns Sound

    A new buffer-based Sound at the stretched tempo.

    Throws

    If this Sound has no AudioBuffer (e.g. streaming/HTML5 audio).