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

EventEmitterMixin

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.

_state: number = Sound.STATES.NONE

The life-cycle state of the sound.

#context: any
#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.

#loading: Promise<void>

Record a Promise while the sound is currently loading.

#events: {} = {}

A mapping of registered events.

Type declaration

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

    The sequence of container loading states.

    Type declaration

    • FAILED: -1
    • NONE: 0
    • LOADING: 1
    • LOADED: 2
    • PLAYING: 3
    • PAUSED: 4
    • STOPPED: 5
    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

    • set volume(value): void
    • Parameters

      • value: number

      Returns void

    • 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

    • set loop(value): void
    • Parameters

      • value: boolean

      Returns void

    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

    • 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

    • 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

    • 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>

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

      Returns Promise<AudioBuffer>

    • 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