Web Audio API 1.1

Editor’s Draft,

More details about this document
This version:
https://webaudio.github.io/web-audio-api/
Latest published version:
https://www.w3.org/TR/webaudio-1.1/
Previous Versions:
Feedback:
public-audio@w3.org with subject line “[webaudio] … message topic …” (archives)
GitHub
Test Suite:
https://github.com/web-platform-tests/wpt/tree/master/webaudio
Editors:
(Mozilla (https://www.mozilla.org/))
(Google (https://www.google.com/))
Former Editors:
Raymond Toy (until Oct 2018)
Chris Wilson (Until Jan 2016)
Chris Rogers (Until Aug 2013)

Abstract

This specification describes a high-level Web API for processing and synthesizing audio in web applications. The primary paradigm is of an audio routing graph, where a number of AudioNode objects are connected together to define the overall audio rendering. The actual processing will primarily take place in the underlying implementation (typically optimized Assembly / C / C++ code), but direct script processing and synthesis is also supported.

The Introduction section covers the motivation behind this specification.

This API is designed to be used in conjunction with other APIs and elements on the web platform, notably: XMLHttpRequest [XHR] (using the responseType and response attributes). For games and interactive applications, it is anticipated to be used with the canvas 2D [2dcontext] and WebGL [WEBGL] 3D graphics APIs.

Status of this document

This is a public copy of the editors’ draft. It is provided for discussion only and may change at any moment. Its publication here does not imply endorsement of its contents by W3C. Don’t cite this document other than as work in progress.

If you wish to make comments regarding this document, please file an issue on the specification repository or send them to public-audio@w3.org (subscribe, archives).

This document was produced by the Web Audio Working Group.

This document was produced by groups operating under the W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent that the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This document is governed by the 18 August 2025 W3C Process Document.

Introduction

Audio on the web has been fairly primitive up to this point and until very recently has had to be delivered through plugins such as Flash and QuickTime. The introduction of the audio element in HTML5 is very important, allowing for basic streaming audio playback. But, it is not powerful enough to handle more complex audio applications. For sophisticated web-based games or interactive applications, another solution is required. It is a goal of this specification to include the capabilities found in modern game audio engines as well as some of the mixing, processing, and filtering tasks that are found in modern desktop audio production applications.

The APIs have been designed with a wide variety of use cases [webaudio-usecases] in mind. Ideally, it should be able to support any use case which could reasonably be implemented with an optimized C++ engine controlled via script and run in a browser. That said, modern desktop audio software can have very advanced capabilities, some of which would be difficult or impossible to build with this system. Apple’s Logic Audio is one such application which has support for external MIDI controllers, arbitrary plugin audio effects and synthesizers, highly optimized direct-to-disk audio file reading/writing, tightly integrated time-stretching, and so on. Nevertheless, the proposed system will be quite capable of supporting a large range of reasonably complex games and interactive applications, including musical ones. And it can be a very good complement to the more advanced graphics features offered by WebGL. The API has been designed so that more advanced capabilities can be added at a later time.

Features

The API supports these primary features:

Modular Routing

Modular routing allows arbitrary connections between different AudioNode objects. Each node can have inputs and/or outputs. A source node has no inputs and a single output. A destination node has one input and no outputs. Other nodes such as filters can be placed between the source and destination nodes. The developer doesn’t have to worry about low-level stream format details when two objects are connected together; the right thing just happens. For example, if a mono audio stream is connected to a stereo input it should just mix to left and right channels appropriately.

In the simplest case, a single source can be routed directly to the output. All routing occurs within an AudioContext containing a single AudioDestinationNode:

modular routing
A simple example of modular routing.

Illustrating this simple routing, here’s a simple example playing a single sound:

const context = new AudioContext();

function playSound() {
    const source = context.createBufferSource();
    source.buffer = dogBarkingBuffer;
    source.connect(context.destination);
    source.start(0);
}

Here’s a more complex example with three sources and a convolution reverb send with a dynamics compressor at the final output stage:

modular routing2
A more complex example of modular routing.
let context;let compressor;let reverb;let source1, source2, source3;let lowpassFilter;let waveShaper;let panner;let dry1, dry2, dry3;let wet1, wet2, wet3;let mainDry;let mainWet;function setupRoutingGraph () {    context = new AudioContext();    // Create the effects nodes.    lowpassFilter = context.createBiquadFilter();    waveShaper = context.createWaveShaper();    panner = context.createPanner();    compressor = context.createDynamicsCompressor();    reverb = context.createConvolver();    // Create main wet and dry.    mainDry = context.createGain();    mainWet = context.createGain();    // Connect final compressor to final destination.    compressor.connect(context.destination);    // Connect main dry and wet to compressor.    mainDry.connect(compressor);    mainWet.connect(compressor);    // Connect reverb to main wet.    reverb.connect(mainWet);    // Create a few sources.    source1 = context.createBufferSource();    source2 = context.createBufferSource();    source3 = context.createOscillator();    source1.buffer = manTalkingBuffer;    source2.buffer = footstepsBuffer;    source3.frequency.value = 440;    // Connect source1    dry1 = context.createGain();    wet1 = context.createGain();    source1.connect(lowpassFilter);    lowpassFilter.connect(dry1);    lowpassFilter.connect(wet1);    dry1.connect(mainDry);    wet1.connect(reverb);    // Connect source2    dry2 = context.createGain();    wet2 = context.createGain();    source2.connect(waveShaper);    waveShaper.connect(dry2);    waveShaper.connect(wet2);    dry2.connect(mainDry);    wet2.connect(reverb);    // Connect source3    dry3 = context.createGain();    wet3 = context.createGain();    source3.connect(panner);    panner.connect(dry3);    panner.connect(wet3);    dry3.connect(mainDry);    wet3.connect(reverb);    // Start the sources now.    source1.start(0);    source2.start(0);    source3.start(0);}

Modular routing also permits the output of AudioNodes to be routed to an AudioParam parameter that controls the behavior of a different AudioNode. In this scenario, the output of a node can act as a modulation signal rather than an input signal.

modular routing3
Modular routing illustrating one Oscillator modulating the frequency of another.
function setupRoutingGraph() {    const context = new AudioContext();    // Create the low frequency oscillator that supplies the modulation signal    const lfo = context.createOscillator();    lfo.frequency.value = 1.0;    // Create the high frequency oscillator to be modulated    const hfo = context.createOscillator();    hfo.frequency.value = 440.0;    // Create a gain node whose gain determines the amplitude of the modulation signal    const modulationGain = context.createGain();    modulationGain.gain.value = 50;    // Configure the graph and start the oscillators    lfo.connect(modulationGain);    modulationGain.connect(hfo.detune);    hfo.connect(context.destination);    hfo.start(0);    lfo.start(0);}

API Overview

The interfaces defined are:

There are also several features that have been deprecated from the Web Audio API but not yet removed, pending implementation experience of their replacements:

1. The Audio API

1.1. The BaseAudioContext Interface

This interface represents a set of AudioNode objects and their connections. It allows for arbitrary routing of signals to an AudioDestinationNode. Nodes are created from the context and are then connected together.

BaseAudioContext is not instantiated directly, but is instead extended by the concrete interfaces AudioContext (for real-time rendering) and OfflineAudioContext (for offline rendering).

BaseAudioContext are created with an internal slot [[pending promises]] that is an initially empty ordered list of promises.

Each BaseAudioContext has a unique media element event task source. Additionally, a BaseAudioContext has several private slots [[rendering thread state]] and [[control thread state]] that take values from AudioContextState, and that are both initially set to "suspended" , [[state before interruption]] that also take values from AudioContextState and is initially set to null and a private slot [[render quantum size]] that is an unsigned integer.

enum AudioContextState {
    "suspended",
    "running",
    "closed",
    "interrupted"
};
AudioContextState enumeration description
Enum value Description
"suspended" This context is currently suspended (context time is not proceeding, audio hardware may be powered down/released).
"running" Audio is being processed.
"closed" This context has been released, and can no longer be used to process audio. All system audio resources have been released.
"interrupted" This context is currently interrupted and cannot process audio until the interruption ends.
enum AudioContextRenderSizeCategory {
    "default",
    "hardware"
};
Enumeration description
"default" The AudioContext’s render quantum size is the default value of 128 frames.
"hardware" The User-Agent picks a render quantum size that is best for the current configuration.

Note: This exposes information about the host and can be used for fingerprinting.

callback DecodeErrorCallback = undefined (DOMException error);

callback DecodeSuccessCallback = undefined (AudioBuffer decodedData);

[Exposed=Window]
interface BaseAudioContext : EventTarget {
    readonly attribute AudioDestinationNode destination;
    readonly attribute float sampleRate;
    readonly attribute double currentTime;
    readonly attribute AudioListener listener;
    readonly attribute AudioContextState state;
    readonly attribute unsigned long renderQuantumSize;
    [SameObject, SecureContext]
    readonly attribute AudioWorklet audioWorklet;
    attribute EventHandler onstatechange;

    AnalyserNode createAnalyser ();
    BiquadFilterNode createBiquadFilter ();
    AudioBuffer createBuffer (unsigned long numberOfChannels,
                                unsigned long length,
                                float sampleRate);
    AudioBufferSourceNode createBufferSource ();
    ChannelMergerNode createChannelMerger (optional unsigned long numberOfInputs = 6);
    ChannelSplitterNode createChannelSplitter (
        optional unsigned long numberOfOutputs = 6);
    ConstantSourceNode createConstantSource ();
    ConvolverNode createConvolver ();
    DelayNode createDelay (optional double maxDelayTime = 1.0);
    DynamicsCompressorNode createDynamicsCompressor ();
    GainNode createGain ();
    IIRFilterNode createIIRFilter (sequence<double> feedforward,
                                    sequence<double> feedback);
    OscillatorNode createOscillator ();
    PannerNode createPanner ();
    PeriodicWave createPeriodicWave (sequence<float> real,
                                        sequence<float> imag,
                                        optional PeriodicWaveConstraints constraints = {});
    ScriptProcessorNode createScriptProcessor(
        optional unsigned long bufferSize = 0,
        optional unsigned long numberOfInputChannels = 2,
        optional unsigned long numberOfOutputChannels = 2);
    StereoPannerNode createStereoPanner ();
    WaveShaperNode createWaveShaper ();

    Promise<AudioBuffer> decodeAudioData (
        ArrayBuffer audioData,
        optional DecodeSuccessCallback? successCallback,
        optional DecodeErrorCallback? errorCallback);
};

1.1.1. Attributes

audioWorklet, of type AudioWorklet, readonly

Allows access to the Worklet object that can import a script containing AudioWorkletProcessor class definitions via the algorithms defined by [HTML] and AudioWorklet.

currentTime, of type double, readonly

This is the time in seconds of the sample frame immediately following the last sample-frame in the block of audio most recently processed by the context’s rendering graph. If the context’s rendering graph has not yet processed a block of audio, then currentTime has a value of zero.

In the time coordinate system of currentTime, the value of zero corresponds to the first sample-frame in the first block processed by the graph. Elapsed time in this system corresponds to elapsed time in the audio stream generated by the BaseAudioContext, which may not be synchronized with other clocks in the system. (For an OfflineAudioContext, since the stream is not being actively played by any device, there is not even an approximation to real time.)

All scheduled times in the Web Audio API are relative to the value of currentTime.

When the BaseAudioContext is in the "running" state, the value of this attribute is monotonically increasing and is updated by the rendering thread in uniform increments, corresponding to one render quantum. Thus, for a running context, currentTime increases steadily as the system processes audio blocks, and always represents the time of the start of the next audio block to be processed. It is also the earliest possible time when any change scheduled in the current state might take effect.

currentTime MUST be read atomically on the control thread before being returned.

destination, of type AudioDestinationNode, readonly

An AudioDestinationNode with a single input representing the final destination for all audio. Usually this will represent the actual audio hardware. All AudioNodes actively rendering audio will directly or indirectly connect to destination.

listener, of type AudioListener, readonly

An AudioListener which is used for 3D spatialization.

onstatechange, of type EventHandler

A property used to set an event handler for an event that is dispatched to BaseAudioContext when the state of the AudioContext has changed (i.e. when the corresponding promise would have resolved). The event type of this event handler is statechange. An event that uses the Event interface will be dispatched to the event handler, which can query the AudioContext’s state directly. A newly-created AudioContext will always begin in the suspended state, and a state change event will be fired whenever the state changes to a different state. This event is fired before the complete event is fired.

sampleRate, of type float, readonly

The sample rate (in sample-frames per second) at which the BaseAudioContext handles audio. It is assumed that all AudioNodes in the context run at this rate. In making this assumption, sample-rate converters or "varispeed" processors are not supported in real-time processing. The Nyquist frequency is half this sample-rate value.

state, of type AudioContextState, readonly

Describes the current state of the BaseAudioContext. Getting this attribute returns the contents of the [[control thread state]] slot.

renderQuantumSize, of type unsigned long, readonly

Getting this attribute returns the value of [[render quantum size]] slot.

1.1.2. Methods

createAnalyser()

Factory method for an AnalyserNode.

No parameters.
Return type: AnalyserNode
createBiquadFilter()

Factory method for a BiquadFilterNode representing a second order filter which can be configured as one of several common filter types.

No parameters.
Return type: BiquadFilterNode
createBuffer(numberOfChannels, length, sampleRate)

Creates an AudioBuffer of the given size. The audio data in the buffer will be zero-initialized (silent). A NotSupportedError exception MUST be thrown if any of the arguments is negative, zero, or outside its nominal range.

Arguments for the BaseAudioContext.createBuffer() method.
Parameter Type Nullable Optional Description
numberOfChannels unsigned long Determines how many channels the buffer will have. An implementation MUST support at least 32 channels.
length unsigned long Determines the size of the buffer in sample-frames. This MUST be at least 1.
sampleRate float Describes the sample-rate of the linear PCM audio data in the buffer in sample-frames per second. See § 2.4 Supported Sample Rates for the required supported range.
Return type: AudioBuffer
createBufferSource()

Factory method for a AudioBufferSourceNode.

No parameters.
Return type: AudioBufferSourceNode
createChannelMerger(numberOfInputs)

Factory method for a ChannelMergerNode representing a channel merger. An IndexSizeError exception MUST be thrown if numberOfInputs is less than 1 or is greater than the number of supported channels.

Arguments for the BaseAudioContext.createChannelMerger(numberOfInputs) method.
Parameter Type Nullable Optional Description
numberOfInputs unsigned long Determines the number of inputs. Values of up to 32 MUST be supported. If not specified, then 6 will be used.
Return type: ChannelMergerNode
createChannelSplitter(numberOfOutputs)

Factory method for a ChannelSplitterNode representing a channel splitter. An IndexSizeError exception MUST be thrown if numberOfOutputs is less than 1 or is greater than the number of supported channels.

Arguments for the BaseAudioContext.createChannelSplitter(numberOfOutputs) method.
Parameter Type Nullable Optional Description
numberOfOutputs unsigned long The number of outputs. Values of up to 32 MUST be supported. If not specified, then 6 will be used.
Return type: ChannelSplitterNode
createConstantSource()

Factory method for a ConstantSourceNode.

No parameters.
Return type: ConstantSourceNode
createConvolver()

Factory method for a ConvolverNode.

No parameters.
Return type: ConvolverNode
createDelay(maxDelayTime)

Factory method for a DelayNode. The initial default delay time will be 0 seconds.

Arguments for the BaseAudioContext.createDelay(maxDelayTime) method.
Parameter Type Nullable Optional Description
maxDelayTime double Specifies the maximum delay time in seconds allowed for the delay line. If specified, this value MUST be greater than zero and less than three minutes or a NotSupportedError exception MUST be thrown. If not specified, then 1 will be used.
Return type: DelayNode
createDynamicsCompressor()

Factory method for a DynamicsCompressorNode.

No parameters.
Return type: DynamicsCompressorNode
createGain()

Factory method for GainNode.

No parameters.
Return type: GainNode
createIIRFilter(feedforward, feedback)
Arguments for the BaseAudioContext.createIIRFilter() method.
Parameter Type Nullable Optional Description
feedforward sequence<double> An array of the feedforward (numerator) coefficients for the transfer function of the IIR filter. The maximum length of this array is 20. If all of the values are zero, an InvalidStateError MUST be thrown. A NotSupportedError MUST be thrown if the array length is 0 or greater than 20.
feedback sequence<double> An array of the feedback (denominator) coefficients for the transfer function of the IIR filter. The maximum length of this array is 20. If the first element of the array is 0, an InvalidStateError MUST be thrown. A NotSupportedError MUST be thrown if the array length is 0 or greater than 20.
Return type: IIRFilterNode
createOscillator()

Factory method for an OscillatorNode.

No parameters.
Return type: OscillatorNode
createPanner()

Factory method for a PannerNode.

No parameters.
Return type: PannerNode
createPeriodicWave(real, imag, constraints)

Factory method to create a PeriodicWave.

When calling this method, execute these steps:
  1. If real and imag are not of the same length, an IndexSizeError MUST be thrown.

  2. Let o be a new object of type PeriodicWaveOptions.

  3. Respectively set the real and imag parameters passed to this factory method to the attributes of the same name on o.

  4. Set the disableNormalization attribute on o to the value of the disableNormalization attribute of the constraints attribute passed to the factory method.

  5. Construct a new PeriodicWave p, passing the BaseAudioContext this factory method has been called on as a first argument, and o.

  6. Return p.

Arguments for the BaseAudioContext.createPeriodicWave() method.
Parameter Type Nullable Optional Description
real sequence<float> A sequence of cosine parameters. See its real constructor argument for a more detailed description.
imag sequence<float> A sequence of sine parameters. See its imag constructor argument for a more detailed description.
constraints PeriodicWaveConstraints If not given, the waveform is normalized. Otherwise, the waveform is normalized according the value given by constraints.
Return type: PeriodicWave
createScriptProcessor(bufferSize, numberOfInputChannels, numberOfOutputChannels)

Factory method for a ScriptProcessorNode. This method is DEPRECATED, as it is intended to be replaced by AudioWorkletNode. Creates a ScriptProcessorNode for direct audio processing using scripts. An IndexSizeError exception MUST be thrown if bufferSize or numberOfInputChannels or numberOfOutputChannels are outside the valid range.

It is invalid for both numberOfInputChannels and numberOfOutputChannels to be zero. In this case an IndexSizeError MUST be thrown.

Arguments for the BaseAudioContext.createScriptProcessor(bufferSize, numberOfInputChannels, numberOfOutputChannels) method.
Parameter Type Nullable Optional Description
bufferSize unsigned long The bufferSize parameter determines the buffer size in units of sample-frames. If it’s not passed in, or if the value is 0, then the implementation will choose the best buffer size for the given environment, which will be constant power of 2 throughout the lifetime of the node. Otherwise if the author explicitly specifies the bufferSize, it MUST be one of the following values: 256, 512, 1024, 2048, 4096, 8192, 16384. This value controls how frequently the audioprocess event is dispatched and how many sample-frames need to be processed each call. Lower values for bufferSize will result in a lower (better) latency. Higher values will be necessary to avoid audio breakup and glitches. It is recommended for authors to not specify this buffer size and allow the implementation to pick a good buffer size to balance between latency and audio quality. If the value of this parameter is not one of the allowed power-of-2 values listed above, an IndexSizeError MUST be thrown.
numberOfInputChannels unsigned long This parameter determines the number of channels for this node’s input. The default value is 2. Values of up to 32 must be supported. A NotSupportedError must be thrown if the number of channels is not supported.
numberOfOutputChannels unsigned long This parameter determines the number of channels for this node’s output. The default value is 2. Values of up to 32 must be supported. A NotSupportedError must be thrown if the number of channels is not supported.
Return type: ScriptProcessorNode
createStereoPanner()

Factory method for a StereoPannerNode.

No parameters.
Return type: StereoPannerNode
createWaveShaper()

Factory method for a WaveShaperNode representing a non-linear distortion.

No parameters.
Return type: WaveShaperNode
decodeAudioData(audioData, successCallback, errorCallback)

Asynchronously decodes the audio file data contained in the ArrayBuffer. The ArrayBuffer can, for example, be loaded from an XMLHttpRequest’s response attribute after setting the responseType to "arraybuffer". Audio file data can be in any of the formats supported by the audio element. The buffer passed to decodeAudioData() has its content-type determined by sniffing, as described in [mimesniff].

Although the primary method of interfacing with this function is via its promise return value, the callback parameters are provided for legacy reasons.

Encourage implementation to warn authors in case of a corrupted file. It isn’t possible to throw because this would be a breaking change.

Note: If the compressed audio data byte-stream is corrupted but the decoding can otherwise proceed, implementations are encouraged to warn authors for example via the developer tools.
When decodeAudioData is called, the following steps MUST be performed on the control thread:
  1. If this’s relevant global object’s associated Document is not fully active then return a promise rejected with "InvalidStateError" DOMException.

  2. Let promise be a new Promise.

  3. If audioData is not detached, execute the following steps:

    1. Append promise to [[pending promises]].

    2. Detach the audioData ArrayBuffer. If this operation throws, jump to step 4.1.

    3. Queue a decoding operation to be performed on another thread.

  4. Else, execute the following error steps:

    1. Let error be a DataCloneError.

    2. Reject promise with error, and remove it from [[pending promises]].

    3. Queue a media element task to invoke errorCallback with error.

  5. Return promise.

When queuing a decoding operation to be performed on another thread, the following steps MUST happen on a thread that is not the control thread nor the rendering thread, called the decoding thread.

Note: Multiple decoding threads can run in parallel to service multiple calls to decodeAudioData.

  1. Let can decode be a boolean flag, initially set to true.

  2. Attempt to determine the MIME type of audioData, using MIME Sniffing § 6.2 Matching an audio or video type pattern. If the audio or video type pattern matching algorithm returns undefined, set can decode to false.

  3. If can decode is true, attempt to decode the encoded audioData into linear PCM. In case of failure, set can decode to false.

    If the media byte-stream contains multiple audio tracks, only decode the first track to linear pcm.

    Note: Authors who need more control over the decoding process can use [WEBCODECS].

  4. If can decode is false, queue a media element task to execute the following steps:

    1. Let error be a DOMException whose name is EncodingError.

      1. Reject promise with error, and remove it from [[pending promises]].

    2. If errorCallback is not missing, invoke errorCallback with error.

  5. Otherwise:

    1. Take the result, representing the decoded linear PCM audio data, and resample it to the sample-rate of the BaseAudioContext if it is different from the sample-rate of audioData.

    2. queue a media element task to execute the following steps:

      1. Let buffer be an AudioBuffer containing the final result (after possibly performing sample-rate conversion).

      2. Resolve promise with buffer.

      3. If successCallback is not missing, invoke successCallback with buffer.

Arguments for the BaseAudioContext.decodeAudioData() method.
Parameter Type Nullable Optional Description
audioData ArrayBuffer An ArrayBuffer containing compressed audio data.
successCallback DecodeSuccessCallback? A callback function which will be invoked when the decoding is finished. The single argument to this callback is an AudioBuffer representing the decoded PCM audio data.
errorCallback DecodeErrorCallback? A callback function which will be invoked if there is an error decoding the audio file.
Return type: Promise<AudioBuffer>

1.1.3. Callback DecodeSuccessCallback() Parameters

decodedData, of type AudioBuffer

The AudioBuffer containing the decoded audio data.

1.1.4. Callback DecodeErrorCallback() Parameters

error, of type DOMException

The error that occurred while decoding.

1.1.5. Lifetime

Once created, an AudioContext will continue to play sound until it has no more sound to play, or the page goes away.

1.1.6. Lack of Introspection or Serialization Primitives

The Web Audio API takes a fire-and-forget approach to audio source scheduling. That is, source nodes are created for each note during the lifetime of the AudioContext, and never explicitly removed from the graph. This is incompatible with a serialization API, since there is no stable set of nodes that could be serialized.

Moreover, having an introspection API would allow content script to be able to observe garbage collections.

1.1.7. System Resources Associated with BaseAudioContext Subclasses

The subclasses AudioContext and OfflineAudioContext should be considered expensive objects. Creating these objects may involve creating a high-priority thread, or using a low-latency system audio stream, both having an impact on energy consumption. It is usually not necessary to create more than one AudioContext in a document.

Constructing or resuming a BaseAudioContext subclass involves acquiring system resources for that context. For AudioContext, this also requires creation of a system audio stream. These operations return when the context begins generating output from its associated audio graph.

Additionally, a user-agent can have an implementation-defined maximum number of AudioContexts, after which any attempt to create a new AudioContext will fail, throwing NotSupportedError.

suspend and close allow authors to release system resources, including threads, processes and audio streams. Suspending a BaseAudioContext permits implementations to release some of its resources, and allows it to continue to operate later by invoking resume. Closing an AudioContext permits implementations to release all of its resources, after which it cannot be used or resumed again.

Note: For example, this can involve waiting for the audio callbacks to fire regularly, or to wait for the hardware to be ready for processing.

1.2. The AudioContext Interface

This interface represents an audio graph whose AudioDestinationNode is routed to a real-time output device that produces a signal directed at the user. In most use cases, only a single AudioContext is used per document.

enum AudioContextLatencyCategory {
        "balanced",
        "interactive",
        "playback"
};
AudioContextLatencyCategory enumeration description
Enum value Description
"balanced" Balance audio output latency and power consumption.
"interactive" Provide the lowest audio output latency possible without glitching. This is the default.
"playback" Prioritize sustained playback without interruption over audio output latency. Lowest power consumption.
enum AudioSinkType {
    "none"
};
AudioSinkType Enumeration description
Enum Value Description
"none" The audio graph will be processed without being played through an audio output device.
[Exposed=Window]
interface AudioContext : BaseAudioContext {
    constructor (optional AudioContextOptions contextOptions = {});
    readonly attribute double baseLatency;
    readonly attribute double outputLatency;
    [SecureContext] readonly attribute (DOMString or AudioSinkInfo) sinkId;
    attribute EventHandler onsinkchange;
    attribute EventHandler onerror;
    [SameObject] readonly attribute AudioPlaybackStats playbackStats;
    AudioTimestamp getOutputTimestamp ();
    Promise<undefined> resume ();
    Promise<undefined> suspend ();
    Promise<undefined> close ();
    [SecureContext] Promise<undefined> setSinkId ((DOMString or AudioSinkOptions) sinkId);
    MediaElementAudioSourceNode createMediaElementSource (HTMLMediaElement mediaElement);
    MediaStreamAudioSourceNode createMediaStreamSource (MediaStream mediaStream);
    MediaStreamTrackAudioSourceNode createMediaStreamTrackSource (
        MediaStreamTrack mediaStreamTrack);
    MediaStreamAudioDestinationNode createMediaStreamDestination ();
};

An AudioContext is said to be allowed to start if the user agent allows the context state to transition from "suspended" to "running". A user agent may disallow this initial transition, and to allow it only when the AudioContext’s relevant global object has sticky activation.

AudioContext has following internal slots:

[[suspended by user]]

A boolean flag representing whether the context is suspended by user code. The initial value is false.

[[sink ID]]

A DOMString or an AudioSinkInfo representing the identifier or the information of the current audio output device respectively. The initial value is "", which means the default audio output device.

[[sink ID at construction]]

A DOMString or an AudioSinkInfo representing the identifier or the information of the audio output device requested at construction, respectively. The initial value is "", which means the default audio output device.

[[pending resume promises]]

An ordered list to store pending Promises created by resume(). It is initially empty.

[[playback stats]]

A slot where the instance of AudioPlaybackStats is stored.

1.2.1. Constructors

AudioContext(contextOptions)

If the current settings object’s relevant global object’s associated Document is NOT fully active, throw an "InvalidStateError" and abort these steps.

When creating an AudioContext, execute these steps:
  1. Let context be a new AudioContext object.

  2. Set a [[control thread state]] to suspended on context.

  3. Set a [[rendering thread state]] to suspended on context.

  4. Set [[state before interruption]] to null on context.

  5. Let messageChannel be a new MessageChannel.

  6. Let controlSidePort be the value of messageChannel’s port1 attribute.

  7. Let renderingSidePort be the value of messageChannel’s port2 attribute.

  8. Let serializedRenderingSidePort be the result of StructuredSerializeWithTransfer(renderingSidePort, « renderingSidePort »).

  9. Set this audioWorklet’s port to controlSidePort.

  10. Queue a control message to set the MessagePort on the AudioContextGlobalScope, with serializedRenderingSidePort.

  11. If contextOptions is given, perform the following substeps:

    1. If sinkId is specified, let sinkId be the value of contextOptions.sinkId and run the following substeps:

      1. If both sinkId and [[sink ID]] are a type of DOMString, and they are equal to each other, abort these substeps.

      2. If sinkId is a type of AudioSinkOptions and [[sink ID]] is a type of AudioSinkInfo, and type in sinkId and type in [[sink ID]] are equal, abort these substeps.

      3. If sinkId is a type of DOMString, set [[sink ID at construction]] to sinkId and abort these substeps.

      4. If sinkId is a type of AudioSinkOptions, set [[sink ID at construction]] to a new instance of AudioSinkInfo created with the value of type of sinkId.

    2. Set the internal latency of context according to contextOptions.latencyHint, as described in latencyHint.

    3. If contextOptions.sampleRate is specified, set the sampleRate of context to this value. Otherwise, follow these substeps:

      1. If sinkId is the empty string or a type of AudioSinkOptions, use the sample rate of the default output device. Abort these substeps.

      2. If sinkId is a DOMString, use the sample rate of the output device identified by sinkId. Abort these substeps.

      If contextOptions.sampleRate differs from the sample rate of the output device, the user agent MUST resample the audio output to match the sample rate of the output device.

      Note: If resampling is required, the latency of context may be affected, possibly by a large amount.

    4. Set the [[render quantum size]] of context based on the value of the contextOptions.renderSizeHint:

      1. If it has the default value of "default", set the [[render quantum size]] private slot to 128.

      2. Else, if it has the value of "hardware", set the [[render quantum size]] private slot to 0.

      3. Else, if an integer has been passed, a NotSupportedError MUST be thrown if the value is outside the range specified in § 2.5 Supported Render Quantum Sizes, otherwise set the [[render quantum size]] private slot to the passed value.

  12. If context is allowed to start, send a control message to start processing.

  13. Set [[playback stats]] to a new instance of AudioPlaybackStats.

  14. Return context.

Sending a control message to start processing means executing the following steps:
  1. Let validationResult be the return value of sink identifier validation of [[sink ID at construction]].

  2. If validationResult is false, execute the following steps:

    1. Set [[sink ID]] to the empty string.

    2. Queue a media element task to fire an event named error at the AudioContext, and abort the following steps.

  3. Attempt to acquire system resources to use a following audio output device based on [[sink ID at construction]] for rendering:

  4. Set [[sink ID]] to the value of [[sink ID at construction]].

  5. Set this [[rendering thread state]] to running on the AudioContext.

  6. Queue a media element task to execute the following steps:

    1. If the [[render quantum size]] of the AudioContext is 0, set it to the actual hardware render quantum size chosen during resource acquisition.

    2. Set the state attribute of the AudioContext to "running".

    3. fire an event named statechange at the AudioContext.

NOTE: In cases where an AudioContext is constructed with no arguments and resource acquisition fails, the User-Agent will attempt to silently render the audio graph using a mechanism that emulates an audio output device.

Sending a control message to set the MessagePort on the AudioWorkletGlobalScope means executing the following steps, on the rendering thread, with serializedRenderingSidePort, that has been transfered to the AudioWorkletGlobalScope:
  1. Let deserializedPort be the result of StructuredDeserialize(serializedRenderingSidePort, the current Realm).

  2. Set port to deserializedPort.

Arguments for the AudioContext.constructor(contextOptions) method.
Parameter Type Nullable Optional Description
contextOptions AudioContextOptions User-specified options controlling how the AudioContext should be constructed.

1.2.2. Attributes

baseLatency, of type double, readonly

This represents the number of seconds of processing latency incurred by the AudioContext passing the audio from the AudioDestinationNode to the audio subsystem. It does not include any additional latency that might be caused by any other processing between the output of the AudioDestinationNode and the audio hardware and specifically does not include any latency incurred the audio graph itself.

For example, if the audio context is running at 44.1 kHz with default render quantum size, and the AudioDestinationNode implements double buffering internally and can process and output audio each render quantum, then the processing latency is \((2\cdot128)/44100 = 5.805 \mathrm{ ms}\), approximately.

outputLatency, of type double, readonly

The estimation in seconds of audio output latency, i.e., the interval between the time the UA requests the host system to play a buffer and the time at which the first sample in the buffer is actually processed by the audio output device. For devices such as speakers or headphones that produce an acoustic signal, this latter time refers to the time when a sample’s sound is produced.

An outputLatency attribute value depends on the platform and the connected audio output device hardware. The outputLatency attribute value may change while the context is running or the associated audio output device changes. It is useful to query this value frequently when accurate synchronization is required.

sinkId, of type (DOMString or AudioSinkInfo), readonly

Returns the value of [[sink ID]] internal slot. This attribute is cached upon update, and it returns the same object after caching.

onsinkchange, of type EventHandler

An event handler for setSinkId(). The event type of this event handler is sinkchange. This event will be dispatched when changing the output device is completed.

NOTE: This is not dispatched for the initial device selection in the construction of AudioContext. The statechange event is available to check the readiness of the initial output device.

onerror, of type EventHandler

An event handler for the Event dispatched from an AudioContext. The event type of this handler is error and the user agent can dispatch this event in the following cases:

  • When initializing and activating a selected audio device encounters failures.

  • When the audio output device associated with an AudioContext is disconnected while the context is running.

  • When the operating system reports an audio device malfunction.

playbackStats, of type AudioPlaybackStats, readonly

An instance of AudioPlaybackStats for this AudioContext. Returns the value of the [[playback stats]] internal slot.

1.2.3. Methods

close()

Closes the AudioContext, releasing the system resources being used. This will not automatically release all AudioContext-created objects, but will suspend the progression of the AudioContext’s currentTime, and stop processing audio data.

When close is called, execute these steps:
  1. If this’s relevant global object’s associated Document is not fully active then return a promise rejected with "InvalidStateError" DOMException.

  2. Let promise be a new Promise.

  3. If the [[control thread state]] flag on the AudioContext is closed reject the promise with InvalidStateError, abort these steps, returning promise.

  4. Set the [[control thread state]] flag on the AudioContext to closed.

  5. Queue a control message to close the AudioContext.

  6. Return promise.

Running a control message to close an AudioContext means running these steps on the rendering thread:
  1. Attempt to release system resources.

  2. Set the [[rendering thread state]] to suspended.

    This will stop rendering.
  3. If this control message is being run in a reaction to the document being unloaded, abort this algorithm.

    There is no need to notify the control thread in this case.
  4. queue a media element task to execute the following steps:

    1. Resolve promise.

    2. If the state attribute of the AudioContext is not already "closed":

      1. Set the state attribute of the AudioContext to "closed".

      2. queue a media element task to fire an event named statechange at the AudioContext.

When an AudioContext is closed, any MediaStreams and HTMLMediaElements that were connected to an AudioContext will have their output ignored. That is, these will no longer cause any output to speakers or other output devices. For more flexibility in behavior, consider using HTMLMediaElement.captureStream().

Note: When an AudioContext has been closed, implementation can choose to aggressively release more resources than when suspending.

No parameters.
Return type: Promise<undefined>
createMediaElementSource(mediaElement)

Creates a MediaElementAudioSourceNode given an HTMLMediaElement. As a consequence of calling this method, audio playback from the HTMLMediaElement will be re-routed into the processing graph of the AudioContext.

Arguments for the AudioContext.createMediaElementSource() method.
Parameter Type Nullable Optional Description
mediaElement HTMLMediaElement The media element that will be re-routed.
Return type: MediaElementAudioSourceNode
createMediaStreamDestination()

Creates a MediaStreamAudioDestinationNode

No parameters.
Return type: MediaStreamAudioDestinationNode
createMediaStreamSource(mediaStream)

Creates a MediaStreamAudioSourceNode.

Arguments for the AudioContext.createMediaStreamSource() method.
Parameter Type Nullable Optional Description
mediaStream MediaStream The media stream that will act as source.
Return type: MediaStreamAudioSourceNode
createMediaStreamTrackSource(mediaStreamTrack)

Creates a MediaStreamTrackAudioSourceNode.

Arguments for the AudioContext.createMediaStreamTrackSource() method.
Parameter Type Nullable Optional Description
mediaStreamTrack MediaStreamTrack The MediaStreamTrack that will act as source. The value of its kind attribute must be equal to "audio", or an InvalidStateError exception MUST be thrown.
Return type: MediaStreamTrackAudioSourceNode
getOutputTimestamp()

Returns a new AudioTimestamp instance containing two related audio stream position values for the context: the contextTime member contains the time of the sample frame which is currently being rendered by the audio output device (i.e., output audio stream position), in the same units and origin as context’s currentTime; the performanceTime member contains the time estimating the moment when the sample frame corresponding to the stored contextTime value was rendered by the audio output device, in the same units and origin as performance.now() (described in [hr-time-3]).

If the context’s rendering graph has not yet processed a block of audio, then getOutputTimestamp call returns an AudioTimestamp instance with both members containing zero.

After the context’s rendering graph has started processing of blocks of audio, its currentTime attribute value always exceeds the contextTime value obtained from getOutputTimestamp method call.

The value returned from getOutputTimestamp method can be used to get performance time estimation for the slightly later context’s time value:
function outputPerformanceTime(contextTime) {
    const timestamp = context.getOutputTimestamp();
    const elapsedTime = contextTime - timestamp.contextTime;
    return timestamp.performanceTime + elapsedTime * 1000;
}

In the above example the accuracy of the estimation depends on how close the argument value is to the current output audio stream position: the closer the given contextTime is to timestamp.contextTime, the better the accuracy of the obtained estimation.

Note: The difference between the values of the context’s currentTime and the contextTime obtained from getOutputTimestamp method call cannot be considered as a reliable output latency estimation because currentTime may be incremented at non-uniform time intervals, so outputLatency attribute should be used instead.

No parameters.
Return type: AudioTimestamp
resume()

Resumes the progression of the AudioContext’s currentTime when it has been suspended.

When resume is called, execute these steps:
  1. If this’s relevant global object’s associated Document is not fully active then return a promise rejected with "InvalidStateError" DOMException.

  2. Let promise be a new Promise.

  3. If the [[control thread state]] on the AudioContext is closed reject the promise with InvalidStateError, abort these steps, returning promise.

  4. Set [[suspended by user]] to false.

  5. If the context’s state attribute is "suspended" and the context’s [[control thread state]] is "interrupted", then:

    1. Queue a media element task to execute the following steps:

      1. Set the state attribute of the AudioContext to "interrupted".

      2. Set the [[state before interruption]] slot to "running".

      3. Queue a media element task to fire an event named statechange at the AudioContext.

    2. Reject the promise with InvalidStateError, abort these steps, returning promise.

  6. If the context is not allowed to start, append promise to [[pending promises]] and [[pending resume promises]] and abort these steps, returning promise.

  7. Set the [[control thread state]] on the AudioContext to running.

  8. Queue a control message to resume the AudioContext with promise.

  9. Return promise.

Running a control message to resume an AudioContext means running these steps on the rendering thread:
  1. Let promise be the promise passed into this algorithm.

  2. Attempt to acquire system resources.

  3. Set the [[rendering thread state]] on the AudioContext to running.

  4. Start rendering the audio graph.

  5. In case of failure, queue a media element task to execute the following steps:

    1. Reject all promises from [[pending resume promises]] in order, then clear [[pending resume promises]].

    2. Additionally, remove those promises from [[pending promises]].

  6. queue a media element task to execute the following steps:

    1. If the [[render quantum size]] of the AudioContext is 0, set it to the actual hardware render quantum size chosen during resource acquisition.

    2. Resolve all promises from [[pending resume promises]] in order.

    3. Clear [[pending resume promises]]. Additionally, remove those promises from [[pending promises]].

    4. Resolve promise.

    5. If the state attribute of the AudioContext is not already "running":

      1. Set the state attribute of the AudioContext to "running".

      2. Queue a media element task to fire an event named statechange at the AudioContext.

No parameters.
Return type: Promise<undefined>
suspend()

Suspends the progression of AudioContext’s currentTime, allows any current context processing blocks that are already processed to be played to the destination, and then allows the system to release its claim on audio hardware. This is generally useful when the application knows it will not need the AudioContext for some time, and wishes to temporarily release system resource associated with the AudioContext. The promise resolves when the frame buffer is empty (has been handed off to the hardware), or immediately (with no other effect) if the context is already suspended. The promise is rejected if the context has been closed.

When suspend is called, execute these steps:
  1. If this’s relevant global object’s associated Document is not fully active then return a promise rejected with "InvalidStateError" DOMException.

  2. Let promise be a new Promise.

  3. If the [[control thread state]] on the AudioContext is closed reject the promise with InvalidStateError, abort these steps, returning promise.

  4. Append promise to [[pending promises]].

  5. Set [[suspended by user]] to true.

  6. Set the [[control thread state]] on the AudioContext to suspended.

  7. Queue a control message to suspend the AudioContext with promise.

  8. Return promise.

Running a control message to suspend an AudioContext means running these steps on the rendering thread:
  1. Let promise be the promise passed into this algorithm.

  2. Attempt to release system resources.

  3. If the [[rendering thread state]] on the AudioContext is "interrupted", queue a media element task to set the [[state before interruption]] slot to "suspended".

  4. Set the [[rendering thread state]] on the AudioContext to "suspended".

  5. Queue a media element task to execute the following steps:

    1. Resolve promise.

    2. If the state attribute of the AudioContext is not already "suspended":

      1. Set the state attribute of the AudioContext to "suspended".

      2. Queue a media element task to fire an event named statechange at the AudioContext.

While an AudioContext is suspended, MediaStreams will have their output ignored; that is, data will be lost by the real time nature of media streams. HTMLMediaElements will similarly have their output ignored until the system is resumed. AudioWorkletNodes and ScriptProcessorNodes will cease to have their processing handlers invoked while suspended, but will resume when the context is resumed. For the purpose of AnalyserNode window functions, the data is considered as a continuous stream - i.e. the resume()/suspend() does not cause silence to appear in the AnalyserNode’s stream of data. In particular, calling AnalyserNode functions repeatedly when a AudioContext is suspended MUST return the same data.

No parameters.
Return type: Promise<undefined>
setSinkId((DOMString or AudioSinkOptions) sinkId)

Sets the identifier of an output device. When this method is invoked, the user agent MUST run the following steps:

  1. Let sinkId be the method’s first argument.

  2. If sinkId is equal to [[sink ID]], return a promise, resolve it immediately and abort these steps.

  3. Let validationResult be the return value of sink identifier validation of sinkId.

  4. If validationResult is false, return a promise rejected with a new DOMException whose name is "NotAllowedError". Abort these steps.

  5. Let p be a new promise.

  6. Send a control message with p and sinkId to start processing.

  7. Return p.

Sending a control message to start processing during setSinkId() means executing the following steps:
  1. Let p be the promise passed into this algorithm.

  2. Let sinkId be the sink identifier passed into this algorithm.

  3. If both sinkId and [[sink ID]] are a type of DOMString, and they are equal to each other, queue a media element task to resolve p and abort these steps.

  4. If sinkId is a type of AudioSinkOptions and [[sink ID]] is a type of AudioSinkInfo, and type in sinkId and type in [[sink ID]] are equal, queue a media element task to resolve p and abort these steps.

  5. Let wasRunning be true.

  6. Set wasRunning to false if the [[rendering thread state]] on the AudioContext is "suspended".

  7. Pause the renderer after processing the current render quantum.

  8. Attempt to release system resources.

  9. If wasRunning is true:

    1. Set the [[rendering thread state]] on the AudioContext to "suspended".

    2. Queue a media element task to execute the following steps:

      1. If the state attribute of the AudioContext is not already "suspended":

        1. Set the state attribute of the AudioContext to "suspended".

        2. Fire an event named statechange at the associated AudioContext.

  10. Attempt to acquire system resources to use a following audio output device based on [[sink ID]] for rendering:

    • The default audio output device for the empty string.

    • A audio output device identified by [[sink ID]].

    In case of failure, reject p with "InvalidAccessError" abort the following steps.

  11. Queue a media element task to execute the following steps:

    1. If sinkId is a type of DOMString, set [[sink ID]] to sinkId. Abort these steps.

    2. If sinkId is a type of AudioSinkOptions and [[sink ID]] is a type of DOMString, set [[sink ID]] to a new instance of AudioSinkInfo created with the value of type of sinkId.

    3. If sinkId is a type of AudioSinkOptions and [[sink ID]] is a type of AudioSinkInfo, set type of [[sink ID]] to the type value of sinkId.

    4. Resolve p.

    5. Fire an event named sinkchange at the associated AudioContext.

  12. If wasRunning is true:

    1. Set the [[rendering thread state]] on the AudioContext to "running".

    2. Queue a media element task to execute the following steps:

      1. If the state attribute of the AudioContext is not already "running":

        1. Set the state attribute of the AudioContext to "running".

        2. Fire an event named statechange at the associated AudioContext.

1.2.4. Validating sinkId

This algorithm is used to validate the information provided to modify sinkId:

  1. Let document be the current settings object’s associated Document.

  2. Let sinkIdArg be the value passed in to this algorithm.

  3. If document is not allowed to use the feature identified by "speaker-selection", return false.

  4. If sinkIdArg is a type of DOMString but it is not equal to the empty string or it does not match any audio output device identified by the result that would be provided by enumerateDevices(), return false.

  5. Return true.

1.2.5. AudioContextOptions

The AudioContextOptions dictionary is used to specify user-specified options for an AudioContext.

dictionary AudioContextOptions {
    (AudioContextLatencyCategory or double) latencyHint = "interactive";
    float sampleRate;
    (DOMString or AudioSinkOptions) sinkId;
    (AudioContextRenderSizeCategory or unsigned long) renderSizeHint = "default";
};
1.2.5.1. Dictionary AudioContextOptions Members
latencyHint, of type (AudioContextLatencyCategory or double), defaulting to "interactive"

Identify the type of playback, which affects tradeoffs between audio output latency and power consumption.

The preferred value of the latencyHint is a value from AudioContextLatencyCategory. However, a double can also be specified for the number of seconds of latency for finer control to balance latency and power consumption. It is at the browser’s discretion to interpret the number appropriately. The actual latency used is given by AudioContext’s baseLatency attribute.

sampleRate, of type float

Set the sampleRate to this value for the AudioContext that will be created. See § 2.4 Supported Sample Rates for the required supported range.

If sampleRate is not specified, the preferred sample rate of the output device for this AudioContext is used.

sinkId, of type (DOMString or AudioSinkOptions)

The identifier or associated information of the audio output device. See sinkId for more details.

renderSizeHint, of type (AudioContextRenderSizeCategory or unsigned long), defaulting to "default"

This allows users to ask for a particular render quantum size when an integer is passed, to use the default of 128 frames if nothing or "default" is passed, or to ask the User-Agent to pick a good render quantum size if "hardware" is specified.

See § 2.5 Supported Render Quantum Sizes for the required supported range.

It is a hint that might not be honored.

1.2.6. AudioSinkOptions

The AudioSinkOptions dictionary is used to specify options for sinkId.

dictionary AudioSinkOptions {
    required AudioSinkType type;
};
1.2.6.1. Dictionary AudioSinkOptions Members
type, of type AudioSinkType

A value of AudioSinkType to specify the type of the device.

1.2.7. AudioSinkInfo

The AudioSinkInfo interface is used to get information on the current audio output device via sinkId.

[Exposed=Window]
interface AudioSinkInfo {
    readonly attribute AudioSinkType type;
};
1.2.7.1. Attributes
type, of type AudioSinkType, readonly

A value of AudioSinkType that represents the type of the device.

1.2.8. AudioTimestamp

dictionary AudioTimestamp {
    double contextTime;
    DOMHighResTimeStamp performanceTime;
};
1.2.8.1. Dictionary AudioTimestamp Members
contextTime, of type double

Represents a point in the time coordinate system of BaseAudioContext’s currentTime.

performanceTime, of type DOMHighResTimeStamp

Represents a point in the time coordinate system of a Performance interface implementation (described in [hr-time-3]).

1.3. The OfflineAudioContext Interface

OfflineAudioContext is a particular type of BaseAudioContext for rendering/mixing-down (potentially) faster than real-time. It does not render to the audio hardware, but instead renders as quickly as possible, fulfilling the returned promise with the rendered result as an AudioBuffer.

[Exposed=Window]
interface OfflineAudioContext : BaseAudioContext {
    constructor(OfflineAudioContextOptions contextOptions);
    constructor(unsigned long numberOfChannels, unsigned long length, float sampleRate);
    Promise<AudioBuffer> startRendering();
    Promise<undefined> resume();
    Promise<undefined> suspend(double suspendTime);
    readonly attribute unsigned long length;
    attribute EventHandler oncomplete;
};

1.3.1. Constructors

OfflineAudioContext(contextOptions)

If the current settings object’s relevant global object’s associated Document is NOT fully active, throw an InvalidStateError and abort these steps.

Let c be a new OfflineAudioContext object. Initialize c as follows:
  1. Set the [[control thread state]] for c to "suspended".

  2. Set the [[rendering thread state]] for c to "suspended".

  3. Set the sampleRate for c, based on the value of contextOptions.sampleRate.

  4. Determine the [[render quantum size]] for c, based on the value of the contextOptions.renderSizeHint:

    1. If it has the default value of "default" or "hardware", set the [[render quantum size]] private slot to 128.

    2. Else, if an integer has been passed, a NotSupportedError MUST be thrown if the value is outside the range specified in § 2.5 Supported Render Quantum Sizes, otherwise set the [[render quantum size]] private slot to the passed value.

  5. Construct an AudioDestinationNode with its channelCount set to contextOptions.numberOfChannels.

  6. Let messageChannel be a new MessageChannel.

  7. Let controlSidePort be the value of messageChannel’s port1 attribute.

  8. Let renderingSidePort be the value of messageChannel’s port2 attribute.

  9. Let serializedRenderingSidePort be the result of StructuredSerializeWithTransfer(renderingSidePort, « renderingSidePort »).

  10. Set this audioWorklet’s port to controlSidePort.

  11. Queue a control message to set the MessagePort on the AudioContextGlobalScope, with serializedRenderingSidePort.

Arguments for the OfflineAudioContext.constructor(contextOptions) method.
Parameter Type Nullable Optional Description
contextOptions The initial parameters needed to construct this context.
OfflineAudioContext(numberOfChannels, length, sampleRate)

The OfflineAudioContext can be constructed with the same arguments as AudioContext.createBuffer. A NotSupportedError exception MUST be thrown if any of the arguments is negative, zero, or outside its nominal range.

The OfflineAudioContext is constructed as if

new OfflineAudioContext({
        numberOfChannels: numberOfChannels,
        length: length,
        sampleRate: sampleRate
})

were called instead.

Arguments for the OfflineAudioContext.constructor(numberOfChannels, length, sampleRate) method.
Parameter Type Nullable Optional Description
numberOfChannels unsigned long Determines how many channels the buffer will have. See createBuffer() for the supported number of channels.
length unsigned long Determines the size of the buffer in sample-frames.
sampleRate float Describes the sample-rate of the linear PCM audio data in the buffer in sample-frames per second. See § 2.4 Supported Sample Rates for the required supported range.

1.3.2. Attributes

length, of type unsigned long, readonly

The size of the buffer in sample-frames. This is the same as the value of the length parameter for the constructor.

oncomplete, of type EventHandler

The event type of this event handler is complete. The event dispatched to the event handler will use the OfflineAudioCompletionEvent interface. It is the last event fired on an OfflineAudioContext.

1.3.3. Methods

startRendering()

Given the current connections and scheduled changes, starts rendering audio.

Although the primary method of getting the rendered audio data is via its promise return value, the instance will also fire an event named complete for legacy reasons.

Let [[rendering started]] be an internal slot of this OfflineAudioContext. Initialize this slot to false.

When startRendering is called, the following steps MUST be performed on the control thread:

  1. If this’s relevant global object’s associated Document is not fully active then return a promise rejected with "InvalidStateError" DOMException.
  2. If the [[rendering started]] slot on the OfflineAudioContext is true, return a rejected promise with InvalidStateError, and abort these steps.
  3. Set the [[rendering started]] slot of the OfflineAudioContext to true.
  4. Let promise be a new promise.
  5. Create a new AudioBuffer, with a number of channels, length and sample rate equal respectively to the numberOfChannels, length and sampleRate values passed to this instance’s constructor in the contextOptions parameter. Assign this buffer to an internal slot [[rendered buffer]] in the OfflineAudioContext.
  6. If an exception was thrown during the preceding AudioBuffer constructor call, reject promise with this exception.
  7. Otherwise, in the case that the buffer was successfully constructed, begin offline rendering.
  8. Append promise to [[pending promises]].
  9. Return promise.
To begin offline rendering, the following steps MUST happen on a rendering thread that is created for the occasion.
  1. Given the current connections and scheduled changes, start rendering length sample-frames of audio into [[rendered buffer]]
  2. For every render quantum, check and suspend rendering if necessary.
  3. If a suspended context is resumed, continue to render the buffer.
  4. Once the rendering is complete,