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, {callback: () => 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 options: AudioTimeoutOptions = {}

      Additional options which modify timeout behavior

    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 options: AudioTimeoutOptions

      Additional options which modify timeout behavior

    Returns Promise<any>

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