A container around an AudioNode which manages sound playback in Foundry Virtual Tabletop. Each Sound is either an AudioBufferSourceNode (for short sources) or a MediaElementAudioSourceNode (for long ones). This class provides an interface around both types which allows standardized control over playback.

Alias

foundry.audio.Sound

See

Hierarchy

  • __type<ObjectConstructor, this> & Object
    • Sound

Constructors

  • Construct a Sound by providing the source URL and other options.

    Parameters

    • src: string

      The audio source path, either a relative path or a remote URL

    • Optional options: {
          context: AudioContext;
          forceBuffer: boolean;
      } = {}

      Additional options which configure the Sound

      • context: AudioContext

        A non-default audio context within which the sound should play

      • forceBuffer: boolean

        Force use of an AudioBufferSourceNode even if the audio duration is long

    Returns Sound

Properties

id: number

A unique integer identifier for this sound.

src: string

The audio source path. Either a relative path served by the running Foundry VTT game server or a remote URL.

gainNode: GainNode

The GainNode used to control volume for this sound.

buffer: AudioBuffer = null

An AudioBuffer instance, if this Sound uses an AudioBufferSourceNode for playback.

element: HTMLAudioElement = null

An HTMLAudioElement, if this Sound uses a MediaElementAudioSourceNode for playback.

destination: AudioNode

The AudioNode destination which is the output target for the Sound.

effects: AudioNode[] = []

A pipeline of AudioNode instances to be applied to Sound playback.

startTime: number

The time in seconds at which playback was started.

pausedTime: number

The time in seconds at which playback was paused.

_manager: Object = null

An internal reference to some object which is managing this Sound instance.

_state: number = Sound.STATES.NONE

The life-cycle state of the sound.

See

#bufferNode: AudioBufferSourceNode

When this Sound uses an AudioBuffer, this is an AudioBufferSourceNode.

#mediaNode: MediaElementAudioSourceNode

When this Sound uses an HTML Audio stream, this is a MediaElementAudioSourceNode.

#playback: SoundPlaybackOptions = ...

Playback configuration options specified at the time that Sound#play is called.

#forceBuffer: boolean = false

Force usage of an AudioBufferSourceNode regardless of audio duration?

#pipeline: AudioNode[] = []

Record the pipeline of nodes currently used by this Sound.

#scheduledEvents: Set<AudioTimeout> = ...

A set of scheduled events orchestrated using the Sound#schedule function.

#operation: Promise<any>

An operation in progress on the sound which must be queued.

#delay: AudioTimeout

A delay timeout before the sound starts or stops.

#events: Record<string, Map<EmittedEventListener, {
    fn: EmittedEventListener;
    once: boolean;
}>> = {}

A mapping of registered events.

STATES: Readonly<{
    FAILED: -1;
    NONE: 0;
    LOADING: 1;
    LOADED: 2;
    STARTING: 3;
    PLAYING: 4;
    PAUSED: 5;
    STOPPING: 6;
    STOPPED: 7;
}> = ...

The sequence of container loading states.

Type declaration

  • FAILED: -1
  • NONE: 0
  • LOADING: 1
  • LOADED: 2
  • STARTING: 3
  • PLAYING: 4
  • PAUSED: 5
  • STOPPING: 6
  • STOPPED: 7
MAX_BUFFER_DURATION: number = ...

The maximum duration, in seconds, for which an AudioBufferSourceNode will be used. Otherwise, a MediaElementAudioSourceNode will be used.

emittedEvents: string[] = ...
#nodeId: number = 0

An incrementing counter used to assign each Sound a unique id.

Accessors

  • get context(): AudioContext
  • The audio context within which this Sound is played.

    Returns AudioContext

  • get sourceNode(): AudioBufferSourceNode | MediaElementAudioSourceNode
  • The AudioSourceNode used to control sound playback.

    Returns AudioBufferSourceNode | MediaElementAudioSourceNode

  • get loaded(): boolean
  • Has the audio file been loaded either fully or for streaming.

    Returns boolean

  • get failed(): boolean
  • Did the audio file fail to load.

    Returns boolean

  • get playing(): boolean
  • Is this sound currently playing?

    Returns boolean

  • get isBuffer(): boolean
  • Does this Sound use an AudioBufferSourceNode? Otherwise, the Sound uses a streamed MediaElementAudioSourceNode.

    Returns boolean

  • get gain(): AudioParam
  • A convenience reference to the GainNode gain audio parameter.

    Returns AudioParam

  • get volume(): number
  • The currently playing volume of the sound. Undefined until playback has started for the first time.

    Returns number

  • get duration(): number
  • The total duration of the audio source in seconds.

    Returns number

  • get currentTime(): number
  • The current playback time of the sound.

    Returns number

  • get loop(): boolean
  • Is the sound looping?

    Returns boolean

Methods

  • Load the audio source and prepare it for playback, either using an AudioBuffer or a streamed HTMLAudioElement.

    Parameters

    • Optional options: {
          autoplay: boolean;
          autoplayOptions: SoundPlaybackOptions;
      } = {}

      Additional options which affect resource loading

      • autoplay: boolean

        Automatically begin playback of the sound once loaded

      • autoplayOptions: SoundPlaybackOptions

        Playback options passed to Sound#play, if autoplay

    Returns Promise<Sound>

    A Promise which resolves to the Sound once it is loaded

  • Begin playback for the Sound. This method is asynchronous because playback may not start until after an initially provided delay. The Promise resolves before the fade-in of any configured volume transition.

    Parameters

    • Optional options: SoundPlaybackOptions = {}

      Options which configure the beginning of sound playback

    • Rest ...args: any

    Returns Promise<Sound>

    A Promise which resolves once playback has started (excluding fade)

  • Pause playback of the Sound. For AudioBufferSourceNode this stops playback after recording the current time. Calling Sound#play will resume playback from the pausedTime unless some other offset is passed. For a MediaElementAudioSourceNode this simply calls the HTMLAudioElement#pause method directly.

    Returns void

  • Stop playback for the Sound. This method is asynchronous because playback may not stop until after an initially provided delay. The Promise resolves after the fade-out of any configured volume transition.

    Parameters

    Returns Promise<Sound>

    A Promise which resolves once playback is fully stopped (including fade)

  • Fade the volume for this sound between its current level and a desired target volume.

    Parameters

    • volume: number

      The desired target volume level between 0 and 1

    • Optional options: {
          duration: number;
          from: number;
          type: string;
      } = {}

      Additional options that configure the fade operation

      • duration: number

        The duration of the fade effect in milliseconds

      • from: number

        A volume level to start from, the current volume by default

      • type: string

        The type of fade easing, "linear" or "exponential"

    Returns Promise<void>

    A Promise that resolves after the requested fade duration

  • Wait a certain scheduled duration within this sound's own AudioContext.

    Parameters

    • duration: number

      The duration to wait in milliseconds

    Returns Promise<void>

    A promise which resolves after the waited duration

  • Schedule a function to occur at the next occurrence of a specific playbackTime for this Sound.

    Parameters

    • fn: SoundScheduleCallback

      A function that will be called with this Sound as its single argument

    • playbackTime: number

      The desired playback time at which the function should be called

    Returns Promise<any>

    A Promise which resolves to the returned value of the provided function once it has been evaluated.

    Example: Schedule audio playback changes

    sound.schedule(() => console.log("Do something exactly 30 seconds into the track"), 30);
    sound.schedule(() => console.log("Do something next time the track loops back to the beginning"), 0);
    sound.schedule(() => console.log("Do something 5 seconds before the end of the track"), sound.duration - 5);
  • Update the array of effects applied to a Sound instance. Optionally a new array of effects can be assigned. If no effects are passed, the current effects are re-applied.

    Parameters

    • Optional effects: AudioNode[]

      An array of AudioNode effects to apply

    Returns void

  • Add a new event listener for a certain type of event.

    Parameters

    • type: string

      The type of event being registered for

    • listener: EmittedEventListener

      The listener function called when the event occurs

    • Optional options: {
          once: boolean;
      } = {}

      Options which configure the event listener

      • once: boolean

        Should the event only be responded to once and then removed

    Returns void

  • Protected

    An inner method which handles loading so that it can be de-duplicated under a single shared Promise resolution. This method is factored out to allow for subclasses to override loading behavior.

    Returns Promise<void>

    A Promise which resolves once the sound is loaded

    Throws

    An error if loading failed for any reason

  • Protected

    Begin playback for the configured pipeline and playback options. This method is factored out so that subclass implementations of Sound can implement alternative behavior.

    Returns void

  • Protected

    Pause playback of the Sound. This method is factored out so that subclass implementations of Sound can implement alternative behavior.

    Returns void

  • Protected

    Stop playback of the Sound. This method is factored out so that subclass implementations of Sound can implement alternative behavior.

    Returns void

  • Protected

    Create any AudioNode instances required for playback of this Sound.

    Returns void

  • Protected

    Create the audio pipeline used to play this Sound. The GainNode is reused each time to link volume changes across multiple playbacks. The AudioSourceNode is re-created every time that Sound#play is called.

    Returns void

  • Protected

    Disconnect the audio pipeline once playback is stopped. Walk backwards along the Sound##pipeline from the Sound#destination, disconnecting each node.

    Returns void

  • An inner method that is wrapped in an enqueued promise. See Sound#play.

    Parameters

    • options: {} = {}

      Returns Promise<void>

    • An inner method that is wrapped in an enqueued promise. See Sound#stop.

      Parameters

      • options: any

      Returns Promise<void>

    • Additional workflows when playback of the Sound begins.

      Returns void

    • Additional workflows when playback of the Sound is paused.

      Returns void

    • Additional workflows when playback of the Sound concludes. This is called by the AudioNode#onended callback.

      Returns Promise<void>

    • Additional workflows when playback of the Sound is stopped, either manually or by concluding its playback.

      Returns void

    • Create an HTML5 Audio element which has loaded the metadata for the provided source.

      Returns Promise<HTMLAudioElement>

      A created HTML Audio element

      Throws

      An error if audio element creation failed

    • Load an audio file and decode it to create an AudioBuffer.

      Returns Promise<AudioBuffer>

      A created AudioBuffer

      Throws

      An error if buffer creation failed

    • Configure playback parameters for the Sound.

      Parameters

      Returns void

    • Cancel any scheduled events which have not yet occurred.

      Returns void

    • Ensure to safely unload a media stream

      Parameters

      • element: HTMLAudioElement

        The audio element to unload

      Returns void