A framework for scheduled audio events with more precise and synchronized timing than using window.setTimeout. This approach creates an empty audio buffer of the desired duration played using the shared game audio context. The onended event of the AudioBufferSourceNode provides a very precise way to synchronize audio events. For audio timing, this is preferable because it avoids numerous issues with window.setTimeout.

Example: Using a callback function

function playForDuration(sound, duration) {
sound.play();
const wait = new AudioTimeout(duration, () => sound.stop())
}

Example: Using an awaited Promise

async function playForDuration(sound, duration) {
sound.play();
const timeout = new AudioTimeout(delay);
await timeout.complete;
sound.stop();
}

Example: Using the wait helper

async function playForDuration(sound, duration) {
sound.play();
await AudioTimeout.wait(duration);
sound.stop();
}

Constructors

  • Create an AudioTimeout by providing a delay and callback.

    Parameters

    • delayMS: number

      A desired delay timing in milliseconds

    • Optional callback: Function

      An optional callback function which is executed at the end of the delay

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

      Additional options which modify timeout behavior

      • context: AudioContext

        The AudioContext within which the timing should be kept. Uses the shared game audio context by default.

    Returns AudioTimeout

Properties

complete: Promise<any>

Is the timeout complete? This can be used to await the completion of the AudioTimeout if necessary. The Promise resolves to the returned value of the provided callback function.

#resolve: Function

The resolution function for the wrapping Promise.

#reject: Function

The rejection function for the wrapping Promise.

#callback: Function

A scheduled callback function

#sourceNode: AudioBufferSourceNode

The source node used to maintain the timeout

Methods

  • Cancel an AudioTimeout by ending it early, rejecting its completion promise, and skipping any callback function.

    Returns void

  • End the timeout, either on schedule or prematurely. Executing any callback function

    Returns void

  • Schedule a task according to some audio timeout.

    Parameters

    • delayMS: number

      A desired delay timing in milliseconds

    • Optional callback: Function

      An optional callback function which is executed at the end of the delay

    • Optional options: any

      Additional options which modify timeout behavior

    Returns Promise<any>

    A promise which resolves as void or as the returned value of the callback

    See

    AudioTimeout#constructor