Web Audio API

W3C Recommendation,

This version:
https://www.w3.org/TR/2021/REC-webaudio-20210617/
Latest published version:
https://www.w3.org/TR/webaudio/
Editor's Draft:
https://webaudio.github.io/web-audio-api/
Previous Versions:
https://www.w3.org/TR/2021/PR-webaudio-20210506/
Feedback:
public-audio@w3.org with subject line “[webaudio] … message topic …” (archives)
Implementation Report:
https://webaudio.github.io/web-audio-api/implementation-report.html
Test Suite:
https://github.com/web-platform-tests/wpt/tree/master/webaudio
Issue Tracking:
GitHub
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)

Please check the errata for any errors or issues reported since publication.


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 section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.

A W3C Recommendation is a specification that, after extensive consensus-building, has received the endorsement of the W3C and its Members. W3C recommends the wide deployment of this specification as a standard for the Web.

This document was produced by the Web Audio Working Group as a Recommendation.

Future updates to this Recommendation may incorporate new features.

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).

An implementation report is available.

This document was produced by a group 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 which 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 15 September 2020 W3C Process Document.

For changes since the last draft, see the Changes section.

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

BaseAudioContext

Firefox53+SafariNoneChrome56+
Opera43+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android53+iOS SafariNoneChrome for Android56+Android WebView56+Samsung Internet6.0+Opera Mobile43+

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 two private slots [[rendering thread state]] and [[control thread state]] that take values from AudioContextState, and that are both initialy set to "suspended".

enum AudioContextState {
  "suspended",
  "running",
  "closed"
};
Enumeration 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.
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;
  [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

BaseAudioContext/audioWorklet

Firefox76+SafariNoneChrome66+
OperaYesEdge79+
Edge (Legacy)NoneIENone
Firefox for Android79+iOS SafariNoneChrome for Android66+Android WebView66+Samsung Internet9.0+Opera MobileYes

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.

BaseAudioContext/currentTime

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

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.

BaseAudioContext/destination

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

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.

BaseAudioContext/listener

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

listener, of type AudioListener, readonly

An AudioListener which is used for 3D spatialization.

BaseAudioContext/onstatechange

In all current engines.

Firefox40+Safari9+Chrome43+
OperaYesEdge79+
Edge (Legacy)14+IENone
Firefox for Android40+iOS Safari9+Chrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes

onstatechange, of type EventHandler

A property used to set the EventHandler 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). An event of type Event 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 oncomplete event is fired.

BaseAudioContext/sampleRate

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

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.

BaseAudioContext/state

In all current engines.

Firefox40+Safari9+Chrome43+
OperaYesEdge79+
Edge (Legacy)14+IENone
Firefox for Android40+iOS Safari9+Chrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes

state, of type AudioContextState, readonly

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

1.1.2. Methods

BaseAudioContext/createAnalyser

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

createAnalyser()

Factory method for an AnalyserNode.

No parameters.
Return type: AnalyserNode

BaseAudioContext/createBiquadFilter

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

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

BaseAudioContext/createBuffer

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

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. An implementation MUST support sample rates in at least the range 8000 to 96000.
Return type: AudioBuffer

BaseAudioContext/createBufferSource

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

createBufferSource()

Factory method for a AudioBufferSourceNode.

No parameters.
Return type: AudioBufferSourceNode

BaseAudioContext/createChannelMerger

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

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

BaseAudioContext/createChannelSplitter

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

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

BaseAudioContext/createConstantSource

Firefox52+SafariNoneChrome56+
Opera43+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android52+iOS SafariNoneChrome for Android56+Android WebView56+Samsung Internet6.0+Opera Mobile43+

createConstantSource()

Factory method for a ConstantSourceNode.

No parameters.
Return type: ConstantSourceNode

BaseAudioContext/createConvolver

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

createConvolver()

Factory method for a ConvolverNode.

No parameters.
Return type: ConvolverNode

BaseAudioContext/createDelay

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

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

BaseAudioContext/createDynamicsCompressor

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

createDynamicsCompressor()

Factory method for a DynamicsCompressorNode.

No parameters.
Return type: DynamicsCompressorNode

BaseAudioContext/createGain

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

createGain()

Factory method for GainNode.

No parameters.
Return type: GainNode

BaseAudioContext/createIIRFilter

Firefox50+SafariNoneChrome49+
OperaYesEdge79+
Edge (Legacy)14+IENone
Firefox for Android50+iOS SafariNoneChrome for Android49+Android WebView49+Samsung Internet5.0+Opera MobileYes

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

BaseAudioContext/createOscillator

In all current engines.

Firefox25+Safari6+Chrome20+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile14+

createOscillator()

Factory method for an OscillatorNode.

No parameters.
Return type: OscillatorNode

BaseAudioContext/createPanner

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

createPanner()

Factory method for a PannerNode.

No parameters.
Return type: PannerNode

BaseAudioContext/createPeriodicWave

In all current engines.

Firefox25+Safari8+Chrome59+
Opera17+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari8+Chrome for Android59+Android WebView59+Samsung Internet7.0+Opera Mobile18+

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

BaseAudioContext/createStereoPanner

Firefox37+SafariNoneChrome42+
OperaNoneEdge79+
Edge (Legacy)12+IENone
Firefox for Android37+iOS SafariNoneChrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileNone

createStereoPanner()

Factory method for a StereoPannerNode.

No parameters.
Return type: StereoPannerNode

BaseAudioContext/createWaveShaper

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

createWaveShaper()

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

No parameters.
Return type: WaveShaperNode

BaseAudioContext/decodeAudioData

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

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.

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 the operation IsDetachedBuffer (described in [ECMASCRIPT]) on audioData is false, execute the following steps:

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

    2. Detach the audioData ArrayBuffer. This operation is described in [ECMASCRIPT]. If this operations throws, jump to the step 3.

    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.

  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

AudioContext

Firefox25+SafariNoneChrome35+
Opera22+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariNoneChrome for Android35+Android WebView37+Samsung Internet3.0+Opera Mobile22+

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"
};
Enumeration 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.
[Exposed=Window]
interface AudioContext : BaseAudioContext {
  constructor (optional AudioContextOptions contextOptions = {});
  readonly attribute double baseLatency;
  readonly attribute double outputLatency;
  AudioTimestamp getOutputTimestamp ();
  Promise<undefined> resume ();
  Promise<undefined> suspend ();
  Promise<undefined> close ();
  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 an internal slot:

[[suspended by user]]

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

1.2.1. Constructors

AudioContext/AudioContext

Firefox25+SafariNoneChrome35+
Opera22+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariNoneChrome for Android35+Android WebView37+Samsung Internet3.0+Opera Mobile22+

AudioContext(contextOptions)

If the current settings object’s responsible document is NOT fully active, throw an InvalidStateError and abort these steps.

When creating an AudioContext, execute these steps:
  1. Set a [[control thread state]] to suspended on the AudioContext.

  2. Set a [[rendering thread state]] to suspended on the AudioContext.

  3. Let [[pending resume promises]] be a slot on this AudioContext, that is an initially empty ordered list of promises.

  4. If contextOptions is given, apply the options:

    1. Set the internal latency of this AudioContext according to contextOptions.latencyHint, as described in latencyHint.

    2. If contextOptions.sampleRate is specified, set the sampleRate of this AudioContext to this value. Otherwise, use the sample rate of the default output device. If the selected sample rate differs from the sample rate of the output device, this AudioContext MUST resample the audio output to match the sample rate of the output device.

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

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

  6. Return this AudioContext object.

Sending a control message to start processing means executing the following steps:
  1. Attempt to acquire system resources. In case of failure, abort the following steps.

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

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

    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.

Note: It is unfortunately not possible to programatically notify authors that the creation of the AudioContext failed. User-Agents are encouraged to log an informative message if they have access to a logging mechanism, such as a developer tools console.

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

AudioContext/baseLatency

Firefox70+SafariNoneChrome58+
Opera45+Edge79+
Edge (Legacy)NoneIENone
Firefox for AndroidNoneiOS SafariNoneChrome for Android58+Android WebView58+Samsung Internet7.0+Opera Mobile43+

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

AudioContext/outputLatency

In only one current engine.

Firefox70+SafariNoneChromeNone
OperaNoneEdgeNone
Edge (Legacy)NoneIENone
Firefox for AndroidNoneiOS SafariNoneChrome for AndroidNoneAndroid WebViewNoneSamsung InternetNoneOpera MobileNone

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.

The outputLatency attribute value depends on the platform and the connected hardware audio output device. The outputLatency attribute value does not change for the context’s lifetime as long as the connected audio output device remains the same. If the audio output device is changed the outputLatency attribute value will be updated accordingly.

1.2.3. Methods

AudioContext/close

In all current engines.

Firefox40+Safari9+Chrome42+
OperaYesEdge79+
Edge (Legacy)14+IENone
Firefox for Android40+iOS Safari9+Chrome for Android43+Android WebView43+Samsung Internet4.0+Opera MobileYes

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>

AudioContext/createMediaElementSource

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

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

AudioContext/createMediaStreamDestination

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

createMediaStreamDestination()

Creates a MediaStreamAudioDestinationNode

No parameters.
Return type: MediaStreamAudioDestinationNode

AudioContext/createMediaStreamSource

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

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

AudioContext/createMediaStreamTrackSource

In only one current engine.

Firefox68+SafariNoneChromeNone
OperaNoneEdgeNone
Edge (Legacy)NoneIENone
Firefox for Android68+iOS SafariNoneChrome for AndroidNoneAndroid WebViewNoneSamsung InternetNoneOpera MobileNone

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

AudioContext/getOutputTimestamp

Firefox70+SafariNoneChrome57+
Opera44+Edge79+
Edge (Legacy)NoneIENone
Firefox for AndroidNoneiOS SafariNoneChrome for Android57+Android WebView57+Samsung Internet7.0+Opera Mobile43+

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

AudioContext/resume

In all current engines.

Firefox40+Safari9+Chrome41+
OperaYesEdge79+
Edge (Legacy)14+IENone
Firefox for AndroidYesiOS Safari9+Chrome for Android41+Android WebView41+Samsung Internet4.0+Opera MobileYes

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 is not allowed to start, append promise to [[pending promises]] and [[pending resume promises]] and abort these steps, returning promise.

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

  7. Queue a control message to resume the AudioContext.

  8. Return promise.

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

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

  3. Start rendering the audio graph.

  4. 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]].

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

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

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

    3. Resolve promise.

    4. 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>

AudioContext/suspend

In all current engines.

Firefox40+Safari9+Chrome43+
OperaYesEdge79+
Edge (Legacy)14+IENone
Firefox for Android40+iOS Safari9+Chrome for Android43+Android WebView43+Samsung Internet4.0+Opera MobileYes

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.

  8. Return promise.

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

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

  3. 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>

1.2.4. AudioContextOptions

AudioContextOptions

Firefox61+SafariNoneChrome60+
Opera?Edge79+
Edge (Legacy)NoneIENone
Firefox for Android61+iOS SafariNoneChrome for Android60+Android WebView60+Samsung Internet8.0+Opera Mobile?

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

dictionary AudioContextOptions {
  (AudioContextLatencyCategory or double) latencyHint = "interactive";
  float sampleRate;
};
1.2.4.1. Dictionary AudioContextOptions Members

AudioContextOptions/latencyHint

Firefox61+SafariNoneChrome60+
Opera?Edge79+
Edge (Legacy)NoneIENone
Firefox for Android61+iOS SafariNoneChrome for Android60+Android WebView60+Samsung Internet8.0+Opera Mobile?

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.

AudioContextOptions/sampleRate

Firefox61+SafariNoneChrome74+
OperaNoneEdge79+
Edge (Legacy)NoneIENone
Firefox for Android61+iOS SafariNoneChrome for Android74+Android WebView74+Samsung Internet11.0+Opera Mobile?

sampleRate, of type float

Set the sampleRate to this value for the AudioContext that will be created. The supported values are the same as the sample rates for an AudioBuffer. A NotSupportedError exception MUST be thrown if the specified sample rate is not supported.

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

1.2.5. AudioTimestamp

dictionary AudioTimestamp {
  double contextTime;
  DOMHighResTimeStamp performanceTime;
};
1.2.5.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

Firefox25+SafariNoneChrome35+
Opera22+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariNoneChrome for Android35+Android WebView4.4.3+Samsung Internet3.0+Opera Mobile22+

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/OfflineAudioContext

Firefox53+SafariNoneChrome35+
Opera22+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android53+iOS SafariNoneChrome for Android35+Android WebView4.4.3+Samsung Internet3.0+Opera Mobile22+

OfflineAudioContext(contextOptions)

If the current settings object’s responsible 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. Construct an AudioDestinationNode with its channelCount set to contextOptions.numberOfChannels.

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 createBuffer() for valid sample rates.

1.3.2. Attributes

OfflineAudioContext/length

FirefoxYesSafariNoneChrome51+
Opera38+Edge79+
Edge (Legacy)14+IENone
Firefox for AndroidYesiOS SafariNoneChrome for Android51+Android WebView51+Samsung Internet5.0+Opera Mobile41+

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.

OfflineAudioContext/oncomplete

In all current engines.

Firefox25+Safari6+Chrome25+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari?Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile14+

oncomplete, of type EventHandler

An EventHandler of type OfflineAudioCompletionEvent. It is the last event fired on an OfflineAudioContext.

1.3.3. Methods

OfflineAudioContext/startRendering

In all current engines.

Firefox25+Safari6+Chrome25+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari?Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile14+

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, queue a media element task to execute the following steps:
    1. Resolve the promise created by startRendering() with [[rendered buffer]].
    2. queue a media element task to fire an event named complete using an instance of OfflineAudioCompletionEvent whose renderedBuffer property is set to [[rendered buffer]].
No parameters.
Return type: Promise<AudioBuffer>

OfflineAudioContext/resume

In only one current engine.

FirefoxNoneSafariNoneChrome49+
Opera36+Edge79+
Edge (Legacy)18IENone
Firefox for AndroidNoneiOS SafariNoneChrome for Android49+Android WebView49+Samsung Internet5.0+Opera Mobile36+

resume()

Resumes the progression of the OfflineAudioContext'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. Abort these steps and reject promise with InvalidStateError when any of following conditions is true:

  4. Set the [[control thread state]] flag on the OfflineAudioContext to running.

  5. Queue a control message to resume the OfflineAudioContext.

  6. Return promise.

Running a control message to resume an OfflineAudioContext means running these steps on the rendering thread:
  1. Set the [[rendering thread state]] on the OfflineAudioContext to running.

  2. Start rendering the audio graph.

  3. In case of failure, queue a media element task to reject promise and abort the remaining steps.

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

    1. Resolve promise.

    2. If the state attribute of the OfflineAudioContext is not already "running":

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

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

No parameters.
Return type: Promise<undefined>

OfflineAudioContext/suspend

In only one current engine.

FirefoxNoneSafariNoneChrome49+
Opera36+Edge79+
Edge (Legacy)18IENone
Firefox for AndroidNoneiOS SafariNoneChrome for Android49+Android WebView49+Samsung Internet5.0+Opera Mobile36+

suspend(suspendTime)

Schedules a suspension of the time progression in the audio context at the specified time and returns a promise. This is generally useful when manipulating the audio graph synchronously on OfflineAudioContext.

Note that the maximum precision of suspension is the size of the render quantum and the specified suspension time will be rounded up to the nearest render quantum boundary. For this reason, it is not allowed to schedule multiple suspends at the same quantized frame. Also, scheduling should be done while the context is not running to ensure precise suspension.

Arguments for the OfflineAudioContext.suspend() method.
Parameter Type Nullable Optional Description
suspendTime double Schedules a suspension of the rendering at the specified time, which is quantized and rounded up to the render quantum size. If the quantized frame number
  1. is negative or
  2. is less than or equal to the current time or
  3. is greater than or equal to the total render duration or
  4. is scheduled by another suspend for the same time,
then the promise is rejected with InvalidStateError.
Return type: Promise<undefined>

1.3.4. OfflineAudioContextOptions

This specifies the options to use in constructing an OfflineAudioContext.

dictionary OfflineAudioContextOptions {
  unsigned long numberOfChannels = 1;
  required unsigned long length;
  required float sampleRate;
};
1.3.4.1. Dictionary OfflineAudioContextOptions Members
length, of type unsigned long

The length of the rendered AudioBuffer in sample-frames.

numberOfChannels, of type unsigned long, defaulting to 1

The number of channels for this OfflineAudioContext.

sampleRate, of type float

The sample rate for this OfflineAudioContext.

1.3.5. The OfflineAudioCompletionEvent Interface

OfflineAudioCompletionEvent

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

OfflineAudioContext/complete_event

In all current engines.

Firefox25+Safari6+Chrome25+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari?Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile14+

This is an Event object which is dispatched to OfflineAudioContext for legacy reasons.

OfflineAudioCompletionEvent/OfflineAudioCompletionEvent

In all current engines.

Firefox53+SafariYesChrome57+
Opera42+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android53+iOS SafariYesChrome for Android57+Android WebView57+Samsung Internet6.0+Opera Mobile42+
[Exposed=Window]
interface OfflineAudioCompletionEvent : Event {
  constructor (DOMString type, OfflineAudioCompletionEventInit eventInitDict);
  readonly attribute AudioBuffer renderedBuffer;
};
1.3.5.1. Attributes

OfflineAudioCompletionEvent/renderedBuffer

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

renderedBuffer, of type AudioBuffer, readonly

An AudioBuffer containing the rendered audio data.

1.3.5.2. OfflineAudioCompletionEventInit
dictionary OfflineAudioCompletionEventInit : EventInit {
  required AudioBuffer renderedBuffer;
};
1.3.5.2.1. Dictionary OfflineAudioCompletionEventInit Members
renderedBuffer, of type AudioBuffer

Value to be assigned to the renderedBuffer attribute of the event.

1.4. The AudioBuffer Interface

AudioBuffer/AudioBuffer

Firefox53+SafariNoneChrome55+
Opera42+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android53+iOS SafariNoneChrome for Android55+Android WebView55+Samsung Internet6.0+Opera Mobile42+

This interface represents a memory-resident audio asset. It can contain one or more channels with each channel appearing to be 32-bit floating-point linear PCM values with a nominal range of \([-1,1]\) but the values are not limited to this range. Typically, it would be expected that the length of the PCM data would be fairly short (usually somewhat less than a minute). For longer sounds, such as music soundtracks, streaming should be used with the audio element and MediaElementAudioSourceNode.

An AudioBuffer may be used by one or more AudioContexts, and can be shared between an OfflineAudioContext and an AudioContext.

AudioBuffer has four internal slots:

[[number of channels]]

The number of audio channels for this AudioBuffer, which is an unsigned long.

[[length]]

The length of each channel of this AudioBuffer, which is an unsigned long.

[[sample rate]]

The sample-rate, in Hz, of this AudioBuffer, a float.

[[internal data]]

A data block holding the audio sample data.

AudioBuffer

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+
[Exposed=Window]
interface AudioBuffer {
  constructor (AudioBufferOptions options);
  readonly attribute float sampleRate;
  readonly attribute unsigned long length;
  readonly attribute double duration;
  readonly attribute unsigned long numberOfChannels;
  Float32Array getChannelData (unsigned long channel);
  undefined copyFromChannel (Float32Array destination,
                             unsigned long channelNumber,
                             optional unsigned long bufferOffset = 0);
  undefined copyToChannel (Float32Array source,
                           unsigned long channelNumber,
                           optional unsigned long bufferOffset = 0);
};

1.4.1. Constructors

AudioBuffer(options)
  1. If any of the values in options lie outside its nominal range, throw a NotSupportedError exception and abort the following steps.

  2. Let b be a new AudioBuffer object.

  3. Respectively assign the values of the attributes numberOfChannels, length, sampleRate of the AudioBufferOptions passed in the constructor to the internal slots [[number of channels]], [[length]], [[sample rate]].

  4. Set the internal slot [[internal data]] of this AudioBuffer to the result of calling CreateByteDataBlock([[length]] * [[number of channels]]).

    Note: This initializes the underlying storage to zero.

  5. Return b.

Arguments for the AudioBuffer.constructor() method.
Parameter Type Nullable Optional Description
options AudioBufferOptions An AudioBufferOptions that determine the properties for this AudioBuffer.

1.4.2. Attributes

AudioBuffer/duration

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

duration, of type double, readonly

Duration of the PCM audio data in seconds.

This is computed from the [[sample rate]] and the [[length]] of the AudioBuffer by performing a division between the [[length]] and the [[sample rate]].

AudioBuffer/length

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

length, of type unsigned long, readonly

Length of the PCM audio data in sample-frames. This MUST return the value of [[length]].

AudioBuffer/numberOfChannels

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

numberOfChannels, of type unsigned long, readonly

The number of discrete audio channels. This MUST return the value of [[number of channels]].

AudioBuffer/sampleRate

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

sampleRate, of type float, readonly

The sample-rate for the PCM audio data in samples per second. This MUST return the value of [[sample rate]].

1.4.3. Methods

AudioBuffer/copyFromChannel

Firefox25+SafariNoneChrome43+
Opera30+Edge79+
Edge (Legacy)13+IENone
Firefox for Android25+iOS SafariNoneChrome for Android43+Android WebView43+Samsung Internet4.0+Opera Mobile30+

copyFromChannel(destination, channelNumber, bufferOffset)

The copyFromChannel() method copies the samples from the specified channel of the AudioBuffer to the destination array.

Let buffer be the AudioBuffer with \(N_b\) frames, let \(N_f\) be the number of elements in the destination array, and \(k\) be the value of bufferOffset. Then the number of frames copied from buffer to destination is \(\max(0, \min(N_b - k, N_f))\). If this is less than \(N_f\), then the remaining elements of destination are not modified.

Arguments for the AudioBuffer.copyFromChannel() method.
Parameter Type Nullable Optional Description
destination Float32Array The array the channel data will be copied to.
channelNumber unsigned long The index of the channel to copy the data from. If channelNumber is greater or equal than the number of channels of the AudioBuffer, an IndexSizeError MUST be thrown.
bufferOffset unsigned long An optional offset, defaulting to 0. Data from the AudioBuffer starting at this offset is copied to the destination.
Return type: undefined

AudioBuffer/copyToChannel

Firefox25+SafariNoneChrome43+
Opera30+Edge79+
Edge (Legacy)13+IENone
Firefox for Android25+iOS SafariNoneChrome for Android43+Android WebView43+Samsung Internet4.0+Opera Mobile30+

copyToChannel(source, channelNumber, bufferOffset)

The copyToChannel() method copies the samples to the specified channel of the AudioBuffer from the source array.

A UnknownError may be thrown if source cannot be copied to the buffer.

Let buffer be the AudioBuffer with \(N_b\) frames, let \(N_f\) be the number of elements in the source array, and \(k\) be the value of bufferOffset. Then the number of frames copied from source to the buffer is \(\max(0, \min(N_b - k, N_f))\). If this is less than \(N_f\), then the remaining elements of buffer are not modified.

Arguments for the AudioBuffer.copyToChannel() method.
Parameter Type Nullable Optional Description
source Float32Array The array the channel data will be copied from.
channelNumber unsigned long The index of the channel to copy the data to. If channelNumber is greater or equal than the number of channels of the AudioBuffer, an IndexSizeError MUST be thrown.
bufferOffset unsigned long An optional offset, defaulting to 0. Data from the source is copied to the AudioBuffer starting at this offset.
Return type: undefined

AudioBuffer/getChannelData

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

getChannelData(channel)

According to the rules described in acquire the content either get a reference to or get a copy of the bytes stored in [[internal data]] in a new Float32Array

A UnknownError may be thrown if the [[internal data]] or the new Float32Array cannot be created.

Arguments for the AudioBuffer.getChannelData() method.
Parameter Type Nullable Optional Description
channel unsigned long This parameter is an index representing the particular channel to get data for. An index value of 0 represents the first channel. This index value MUST be less than [[number of channels]] or an IndexSizeError exception MUST be thrown.
Return type: Float32Array

Note: The methods copyToChannel() and copyFromChannel() can be used to fill part of an array by passing in a Float32Array that’s a view onto the larger array. When reading data from an AudioBuffer's channels, and the data can be processed in chunks, copyFromChannel() should be preferred to calling getChannelData() and accessing the resulting array, because it may avoid unnecessary memory allocation and copying.

An internal operation acquire the contents of an AudioBuffer is invoked when the contents of an AudioBuffer are needed by some API implementation. This operation returns immutable channel data to the invoker.

When an acquire the content operation occurs on an AudioBuffer, run the following steps:
  1. If the operation IsDetachedBuffer on any of the AudioBuffer's ArrayBuffers return true, abort these steps, and return a zero-length channel data buffer to the invoker.

  2. Detach all ArrayBuffers for arrays previously returned by getChannelData() on this AudioBuffer.

    Note: Because AudioBuffer can only be created via createBuffer() or via the AudioBuffer constructor, this cannot throw.

  3. Retain the underlying [[internal data]] from those ArrayBuffers and return references to them to the invoker.

  4. Attach ArrayBuffers containing copies of the data to the AudioBuffer, to be returned by the next call to getChannelData().

The acquire the contents of an AudioBuffer operation is invoked in the following cases:

Note: This means that copyToChannel() cannot be used to change the content of an AudioBuffer currently in use by an AudioNode that has acquired the content of an AudioBuffer since the AudioNode will continue to use the data previously acquired.

1.4.4. AudioBufferOptions

This specifies the options to use in constructing an AudioBuffer. The length and sampleRate members are required.

dictionary AudioBufferOptions {
  unsigned long numberOfChannels = 1;
  required unsigned long length;
  required float sampleRate;
};
1.4.4.1. Dictionary AudioBufferOptions Members

The allowed values for the members of this dictionary are constrained. See createBuffer().

length, of type unsigned long

The length in sample frames of the buffer. See length for constraints.

numberOfChannels, of type unsigned long, defaulting to 1

The number of channels for the buffer. See numberOfChannels for constraints.

sampleRate, of type float

The sample rate in Hz for the buffer. See sampleRate for constraints.

1.5. The AudioNode Interface

AudioNodes are the building blocks of an AudioContext. This interface represents audio sources, the audio destination, and intermediate processing modules. These modules can be connected together to form processing graphs for rendering audio to the audio hardware. Each node can have inputs and/or outputs. A source node has no inputs and a single output. Most processing nodes such as filters will have one input and one output. Each type of AudioNode differs in the details of how it processes or synthesizes audio. But, in general, an AudioNode will process its inputs (if it has any), and generate audio for its outputs (if it has any).

Each output has one or more channels. The exact number of channels depends on the details of the specific AudioNode.

An output may connect to one or more AudioNode inputs, thus fan-out is supported. An input initially has no connections, but may be connected from one or more AudioNode outputs, thus fan-in is supported. When the connect() method is called to connect an output of an AudioNode to an input of an AudioNode, we call that a connection to the input.

Each AudioNode input has a specific number of channels at any given time. This number can change depending on the connection(s) made to the input. If the input has no connections then it has one channel which is silent.

For each input, an AudioNode performs a mixing of all connections to that input. Please see § 4 Channel Up-Mixing and Down-Mixing for normative requirements and details.

The processing of inputs and the internal operations of an AudioNode take place continuously with respect to AudioContext time, regardless of whether the node has connected outputs, and regardless of whether these outputs ultimately reach an AudioContext's AudioDestinationNode.

AudioNode

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+
[Exposed=Window]
interface AudioNode : EventTarget {
  AudioNode connect (AudioNode destinationNode,
                     optional unsigned long output = 0,
                     optional unsigned long input = 0);
  undefined connect (AudioParam destinationParam, optional unsigned long output = 0);
  undefined disconnect ();
  undefined disconnect (unsigned long output);
  undefined disconnect (AudioNode destinationNode);
  undefined disconnect (AudioNode destinationNode, unsigned long output);
  undefined disconnect (AudioNode destinationNode,
                        unsigned long output,
                        unsigned long input);
  undefined disconnect (AudioParam destinationParam);
  undefined disconnect (AudioParam destinationParam, unsigned long output);
  readonly attribute BaseAudioContext context;
  readonly attribute unsigned long numberOfInputs;
  readonly attribute unsigned long numberOfOutputs;
  attribute unsigned long channelCount;
  attribute ChannelCountMode channelCountMode;
  attribute ChannelInterpretation channelInterpretation;
};

1.5.1. AudioNode Creation

AudioNodes can be created in two ways: by using the constructor for this particular interface, or by using the factory method on the BaseAudioContext or AudioContext.

The BaseAudioContext passed as first argument of the constructor of an AudioNodes is called the associated BaseAudioContext of the AudioNode to be created. Similarly, when using the factory method, the associated BaseAudioContext of the AudioNode is the BaseAudioContext this factory method is called on.

To create a new AudioNode of a particular type n using its factory method, called on a BaseAudioContext c, execute these steps:
  1. Let node be a new object of type n.

  2. Let option be a dictionary of the type associated to the interface associated to this factory method.

  3. For each parameter passed to the factory method, set the dictionary member of the same name on option to the value of this parameter.

  4. Call the constructor for n on node with c and option as arguments.

  5. Return node

Initializing an object o that inherits from AudioNode means executing the following steps, given the arguments context and dict passed to the constructor of this interface.
  1. Set o’s associated BaseAudioContext to context.

  2. Set its value for numberOfInputs, numberOfOutputs, channelCount, channelCountMode, channelInterpretation to the default value for this specific interface outlined in the section for each AudioNode.

  3. For each member of dict passed in, execute these steps, with k the key of the member, and v its value. If any exceptions is thrown when executing these steps, abort the iteration and propagate the exception to the caller of the algorithm (constructor or factory method).

    1. If k is the name of an AudioParam on this interface, set the value attribute of this AudioParam to v.

    2. Else if k is the name of an attribute on this interface, set the object associated with this attribute to v.

The associated interface for a factory method is the interface of the objects that are returned from this method. The associated option object for an interface is the option object that can be passed to the constructor for this interface.

AudioNodes are EventTargets, as described in [DOM]. This means that it is possible to dispatch events to AudioNodes the same way that other EventTargets accept events.

enum ChannelCountMode {
  "max",
  "clamped-max",
  "explicit"
};

The ChannelCountMode, in conjuction with the node’s channelCount and channelInterpretation values, is used to determine the computedNumberOfChannels that controls how inputs to a node are to be mixed. The computedNumberOfChannels is determined as shown below. See § 4 Channel Up-Mixing and Down-Mixing for more information on how mixing is to be done.

Enumeration description
"max" computedNumberOfChannels is the maximum of the number of channels of all connections to an input. In this mode channelCount is ignored.
"clamped-max" computedNumberOfChannels is determined as for "max" and then clamped to a maximum value of the given channelCount.
"explicit" computedNumberOfChannels is the exact value as specified by the channelCount.
enum ChannelInterpretation {
  "speakers",
  "discrete"
};
Enumeration description
"speakers" use up-mix equations or down-mix equations. In cases where the number of channels do not match any of these basic speaker layouts, revert to "discrete".
"discrete" Up-mix by filling channels until they run out then zero out remaining channels. Down-mix by filling as many channels as possible, then dropping remaining channels.

1.5.2. AudioNode Tail-Time

An AudioNode can have a tail-time. This means that even when the AudioNode is fed silence, the output can be non-silent.

AudioNodes have a non-zero tail-time if they have internal processing state such that input in the past affects the future output. AudioNodes may continue to produce non-silent output for the calculated tail-time even after the input transitions from non-silent to silent.

1.5.3. AudioNode Lifetime

AudioNode can be actively processing during a render quantum, if any of the following conditions hold.

Note: This takes into account AudioNodes that have a tail-time.

AudioNodes that are not actively processing output a single channel of silence.

1.5.4. Attributes

AudioNode/channelCount

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

channelCount, of type unsigned long

channelCount is the number of channels used when up-mixing and down-mixing connections to any inputs to the node. The default value is 2 except for specific nodes where its value is specially determined. This attribute has no effect for nodes with no inputs. If this value is set to zero or to a value greater than the implementation’s maximum number of channels the implementation MUST throw a NotSupportedError exception.

In addition, some nodes have additional channelCount constraints on the possible values for the channel count:

AudioDestinationNode

The behavior depends on whether the destination node is the destination of an AudioContext or OfflineAudioContext:

AudioContext

The channel count MUST be between 1 and maxChannelCount. An IndexSizeError exception MUST be thrown for any attempt to set the count outside this range.

OfflineAudioContext

The channel count cannot be changed. An InvalidStateError exception MUST be thrown for any attempt to change the value.

AudioWorkletNode

See § 1.32.3.3.2 Configuring Channels with AudioWorkletNodeOptions Configuring Channels with AudioWorkletNodeOptions.

ChannelMergerNode

The channel count cannot be changed, and an InvalidStateError exception MUST be thrown for any attempt to change the value.

ChannelSplitterNode

The channel count cannot be changed, and an InvalidStateError exception MUST be thrown for any attempt to change the value.

ConvolverNode

The channel count cannot be greater than two, and a NotSupportedError exception MUST be thrown for any attempt to change it to a value greater than two.

DynamicsCompressorNode

The channel count cannot be greater than two, and a NotSupportedError exception MUST be thrown for any attempt to change it to a value greater than two.

PannerNode

The channel count cannot be greater than two, and a NotSupportedError exception MUST be thrown for any attempt to change it to a value greater than two.

ScriptProcessorNode

The channel count cannot be changed, and an NotSupportedError exception MUST be thrown for any attempt to change the value.

StereoPannerNode

The channel count cannot be greater than two, and a NotSupportedError exception MUST be thrown for any attempt to change it to a value greater than two.

See § 4 Channel Up-Mixing and Down-Mixing for more information on this attribute.

AudioNode/channelCountMode

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

channelCountMode, of type ChannelCountMode

channelCountMode determines how channels will be counted when up-mixing and down-mixing connections to any inputs to the node. The default value is "max". This attribute has no effect for nodes with no inputs.

In addition, some nodes have additional channelCountMode constraints on the possible values for the channel count mode:

AudioDestinationNode

If the AudioDestinationNode is the destination node of an OfflineAudioContext, then the channel count mode cannot be changed. An InvalidStateError exception MUST be thrown for any attempt to change the value.

ChannelMergerNode

The channel count mode cannot be changed from "explicit" and an InvalidStateError exception MUST be thrown for any attempt to change the value.

ChannelSplitterNode

The channel count mode cannot be changed from "explicit" and an InvalidStateError exception MUST be thrown for any attempt to change the value.

ConvolverNode

The channel count mode cannot be set to "max", and a NotSupportedError exception MUST be thrown for any attempt to set it to "max".

DynamicsCompressorNode

The channel count mode cannot be set to "max", and a NotSupportedError exception MUST be thrown for any attempt to set it to "max".

PannerNode

The channel count mode cannot be set to "max", and a NotSupportedError exception MUST be thrown for any attempt to set it to "max".

ScriptProcessorNode

The channel count mode cannot be changed from "explicit" and an NotSupportedError exception MUST be thrown for any attempt to change the value.

StereoPannerNode

The channel count mode cannot be set to "max", and a NotSupportedError exception MUST be thrown for any attempt to set it to "max".

See the § 4 Channel Up-Mixing and Down-Mixing section for more information on this attribute.

AudioNode/channelInterpretation

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

channelInterpretation, of type ChannelInterpretation

channelInterpretation determines how individual channels will be treated when up-mixing and down-mixing connections to any inputs to the node. The default value is "speakers". This attribute has no effect for nodes with no inputs.

In addition, some nodes have additional channelInterpretation constraints on the possible values for the channel interpretation:

ChannelSplitterNode

The channel intepretation can not be changed from "discrete" and a InvalidStateError exception MUST be thrown for any attempt to change the value.

See § 4 Channel Up-Mixing and Down-Mixing for more information on this attribute.

AudioNode/context

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

context, of type BaseAudioContext, readonly

The BaseAudioContext which owns this AudioNode.

AudioNode/numberOfInputs

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

numberOfInputs, of type unsigned long, readonly

The number of inputs feeding into the AudioNode. For source nodes, this will be 0. This attribute is predetermined for many AudioNode types, but some AudioNodes, like the ChannelMergerNode and the AudioWorkletNode, have variable number of inputs.

AudioNode/numberOfOutputs

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

numberOfOutputs, of type unsigned long, readonly

The number of outputs coming out of the AudioNode. This attribute is predetermined for some AudioNode types, but can be variable, like for the ChannelSplitterNode and the AudioWorkletNode.

1.5.5. Methods

AudioNode/connect

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

connect(destinationNode, output, input)

There can only be one connection between a given output of one specific node and a given input of another specific node. Multiple connections with the same termini are ignored.

For example:
nodeA.connect(nodeB);
nodeA.connect(nodeB);

will have the same effect as

nodeA.connect(nodeB);

This method returns destination AudioNode object.

Arguments for the AudioNode.connect(destinationNode, output, input) method.
Parameter Type Nullable Optional Description
destinationNode The destination parameter is the AudioNode to connect to. If the destination parameter is an AudioNode that has been created using another AudioContext, an InvalidAccessError MUST be thrown. That is, AudioNodes cannot be shared between AudioContexts. Multiple AudioNodes can be connected to the same AudioNode, this is described in Channel Upmixing and down mixing section.
output unsigned long The output parameter is an index describing which output of the AudioNode from which to connect. If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown. It is possible to connect an AudioNode output to more than one input with multiple calls to connect(). Thus, "fan-out" is supported.
input The input parameter is an index describing which input of the destination AudioNode to connect to. If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown. It is possible to connect an AudioNode to another AudioNode which creates a cycle: an AudioNode may connect to another AudioNode, which in turn connects back to the input or AudioParam of the first AudioNode.
Return type: AudioNode

AudioNode/connect

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

connect(destinationParam, output)

Connects the AudioNode to an AudioParam, controlling the parameter value with an a-rate signal.

It is possible to connect an AudioNode output to more than one AudioParam with multiple calls to connect(). Thus, "fan-out" is supported.

It is possible to connect more than one AudioNode output to a single AudioParam with multiple calls to connect(). Thus, "fan-in" is supported.

An AudioParam will take the rendered audio data from any AudioNode output connected to it and convert it to mono by down-mixing if it is not already mono, then mix it together with other such outputs and finally will mix with the intrinsic parameter value (the value the AudioParam would normally have without any audio connections), including any timeline changes scheduled for the parameter.

The down-mixing to mono is equivalent to the down-mixing for an AudioNode with channelCount = 1, channelCountMode = "explicit", and channelInterpretation = "speakers".

There can only be one connection between a given output of one specific node and a specific AudioParam. Multiple connections with the same termini are ignored.

For example:
nodeA.connect(param);
nodeA.connect(param);

will have the same effect as

nodeA.connect(param);
Arguments for the AudioNode.connect(destinationParam, output) method.
Parameter Type Nullable Optional Description
destinationParam AudioParam The destination parameter is the AudioParam to connect to. This method does not return the destination AudioParam object. If destinationParam belongs to an AudioNode that belongs to a BaseAudioContext that is different from the BaseAudioContext that has created the AudioNode on which this method was called, an InvalidAccessError MUST be thrown.
output unsigned long The output parameter is an index describing which output of the AudioNode from which to connect. If the parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
Return type: undefined

AudioNode/disconnect

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

disconnect()

Disconnects all outgoing connections from the AudioNode.

No parameters.
Return type: undefined
disconnect(output)

Disconnects a single output of the AudioNode from any other AudioNode or AudioParam objects to which it is connected.

Arguments for the AudioNode.disconnect(output) method.
Parameter Type Nullable Optional Description
output unsigned long This parameter is an index describing which output of the AudioNode to disconnect. It disconnects all outgoing connections from the given output. If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
Return type: undefined
disconnect(destinationNode)

Disconnects all outputs of the AudioNode that go to a specific destination AudioNode.

Arguments for the AudioNode.disconnect(destinationNode) method.
Parameter Type Nullable Optional Description
destinationNode The destinationNode parameter is the AudioNode to disconnect. It disconnects all outgoing connections to the given destinationNode. If there is no connection to the destinationNode, an InvalidAccessError exception MUST be thrown.
Return type: undefined
disconnect(destinationNode, output)

Disconnects a specific output of the AudioNode from any and all inputs of some destination AudioNode.

Arguments for the AudioNode.disconnect(destinationNode, output) method.
Parameter Type Nullable Optional Description
destinationNode The destinationNode parameter is the AudioNode to disconnect. If there is no connection to the destinationNode from the given output, an InvalidAccessError exception MUST be thrown.
output unsigned long The output parameter is an index describing which output of the AudioNode from which to disconnect. If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
Return type: undefined
disconnect(destinationNode, output, input)

Disconnects a specific output of the AudioNode from a specific input of some destination AudioNode.

Arguments for the AudioNode.disconnect(destinationNode, output, input) method.
Parameter Type Nullable Optional Description
destinationNode The destinationNode parameter is the AudioNode to disconnect. If there is no connection to the destinationNode from the given input to the given output, an InvalidAccessError exception MUST be thrown.
output unsigned long The output parameter is an index describing which output of the AudioNode from which to disconnect. If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
input The input parameter is an index describing which input of the destination AudioNode to disconnect. If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
Return type: undefined
disconnect(destinationParam)

Disconnects all outputs of the AudioNode that go to a specific destination AudioParam. The contribution of this AudioNode to the computed parameter value goes to 0 when this operation takes effect. The intrinsic parameter value is not affected by this operation.

Arguments for the AudioNode.disconnect(destinationParam) method.
Parameter Type Nullable Optional Description
destinationParam AudioParam The destinationParam parameter is the AudioParam to disconnect. If there is no connection to the destinationParam, an InvalidAccessError exception MUST be thrown.
Return type: undefined
disconnect(destinationParam, output)

Disconnects a specific output of the AudioNode from a specific destination AudioParam. The contribution of this AudioNode to the computed parameter value goes to 0 when this operation takes effect. The intrinsic parameter value is not affected by this operation.

Arguments for the AudioNode.disconnect(destinationParam, output) method.
Parameter Type Nullable Optional Description
destinationParam AudioParam The destinationParam parameter is the AudioParam to disconnect. If there is no connection to the destinationParam, an InvalidAccessError exception MUST be thrown.
output unsigned long The output parameter is an index describing which output of the AudioNode from which to disconnect. If the parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
Return type: undefined

1.5.6. AudioNodeOptions

This specifies the options that can be used in constructing all AudioNodes. All members are optional. However, the specific values used for each node depends on the actual node.

AudioNodeOptions

Firefox53+Safari?Chrome55+
Opera42+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android53+iOS Safari?Chrome for Android55+Android WebView55+Samsung Internet6.0+Opera Mobile42+
dictionary AudioNodeOptions {
  unsigned long channelCount;
  ChannelCountMode channelCountMode;
  ChannelInterpretation channelInterpretation;
};
1.5.6.1. Dictionary AudioNodeOptions Members
channelCount, of type unsigned long

Desired number of channels for the channelCount attribute.

channelCountMode, of type ChannelCountMode

Desired mode for the channelCountMode attribute.

channelInterpretation, of type ChannelInterpretation

Desired mode for the channelInterpretation attribute.

1.6. The AudioParam Interface

AudioParam

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

AudioParam controls an individual aspect of an AudioNode's functionality, such as volume. The parameter can be set immediately to a particular value using the value attribute. Or, value changes can be scheduled to happen at very precise times (in the coordinate system of AudioContext's currentTime attribute), for envelopes, volume fades, LFOs, filter sweeps, grain windows, etc. In this way, arbitrary timeline-based automation curves can be set on any AudioParam. Additionally, audio signals from the outputs of AudioNodes can be connected to an AudioParam, summing with the intrinsic parameter value.

Some synthesis and processing AudioNodes have AudioParams as attributes whose values MUST be taken into account on a per-audio-sample basis. For other AudioParams, sample-accuracy is not important and the value changes can be sampled more coarsely. Each individual AudioParam will specify that it is either an a-rate parameter which means that its values MUST be taken into account on a per-audio-sample basis, or it is a k-rate parameter.

Implementations MUST use block processing, with each AudioNode processing one render quantum.

For each render quantum, the value of a k-rate parameter MUST be sampled at the time of the very first sample-frame, and that value MUST be used for the entire block. a-rate parameters MUST be sampled for each sample-frame of the block. Depending on the AudioParam, its rate can be controlled by setting the automationRate attribute to either "a-rate" or "k-rate". See the description of the individual AudioParams for further details.

Each AudioParam includes minValue and maxValue attributes that together form the simple nominal range for the parameter. In effect, value of the parameter is clamped to the range \([\mathrm{minValue}, \mathrm{maxValue}]\). See § 1.6.3 Computation of Value for full details.

For many AudioParams the minValue and maxValue is intended to be set to the maximum possible range. In this case, maxValue should be set to the most-positive-single-float value, which is 3.4028235e38. (However, in JavaScript which only supports IEEE-754 double precision float values, this must be written as 3.4028234663852886e38.) Similarly, minValue should be set to the most-negative-single-float value, which is the negative of the most-positive-single-float: -3.4028235e38. (Similarly, this must be written in JavaScript as -3.4028234663852886e38.)

An AudioParam maintains a list of zero or more automation events. Each automation event specifies changes to the parameter’s value over a specific time range, in relation to its automation event time in the time coordinate system of the AudioContext's currentTime attribute. The list of automation events is maintained in ascending order of automation event time.

The behavior of a given automation event is a function of the AudioContext's current time, as well as the automation event times of this event and of adjacent events in the list. The following automation methods change the event list by adding a new event to the event list, of a type specific to the method:

The following rules will apply when calling these methods:

Note: AudioParam attributes are read only, with the exception of the value attribute.

The automation rate of an AudioParam can be selected setting the automationRate attribute with one of the following values. However, some AudioParams have constraints on whether the automation rate can be changed.

enum AutomationRate {
  "a-rate",
  "k-rate"
};
Enumeration description
"a-rate" This AudioParam is set for a-rate processing.
"k-rate" This AudioParam is set for k-rate processing.

Each AudioParam has an internal slot [[current value]], initially set to the AudioParam's defaultValue.

[Exposed=Window]
interface AudioParam {
  attribute float value;
  attribute AutomationRate automationRate;
  readonly attribute float defaultValue;
  readonly attribute float minValue;
  readonly attribute float maxValue;
  AudioParam setValueAtTime (float value, double startTime);
  AudioParam linearRampToValueAtTime (float value, double endTime);
  AudioParam exponentialRampToValueAtTime (float value, double endTime);
  AudioParam setTargetAtTime (float target, double startTime, float timeConstant);
  AudioParam setValueCurveAtTime (sequence<float> values,
                                  double startTime,
                                  double duration);
  AudioParam cancelScheduledValues (double cancelTime);
  AudioParam cancelAndHoldAtTime (double cancelTime);
};

1.6.1. Attributes

automationRate, of type AutomationRate

The automation rate for the AudioParam. The default value depends on the actual AudioParam; see the description of each individual AudioParam for the default value.

Some nodes have additional automation rate constraints as follows:

AudioBufferSourceNode

The AudioParams playbackRate and detune MUST be "k-rate". An InvalidStateError must be thrown if the rate is changed to "a-rate".

DynamicsCompressorNode

The AudioParams threshold, knee, ratio, attack, and release MUST be "k-rate". An InvalidStateError must be thrown if the rate is changed to "a-rate".

PannerNode

If the panningModel is "HRTF", the setting of the automationRate for any AudioParam of the PannerNode is ignored. Likewise, the setting of the automationRate for any AudioParam of the AudioListener is ignored. In this case, the AudioParam behaves as if the automationRate were set to "k-rate".

AudioParam/defaultValue

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

defaultValue, of type float, readonly

Initial value for the value attribute.

AudioParam/maxValue

In all current engines.

Firefox53+Safari6+Chrome52+
Opera39+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android53+iOS SafariYesChrome for Android52+Android WebView52+Samsung Internet6.0+Opera Mobile41+

maxValue, of type float, readonly

The nominal maximum value that the parameter can take. Together with minValue, this forms the nominal range for this parameter.

AudioParam/minValue

In all current engines.

Firefox53+Safari6+Chrome52+
Opera39+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android53+iOS SafariYesChrome for Android52+Android WebView52+Samsung Internet6.0+Opera Mobile41+

minValue, of type float, readonly

The nominal minimum value that the parameter can take. Together with maxValue, this forms the nominal range for this parameter.

AudioParam/value

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

value, of type float

The parameter’s floating-point value. This attribute is initialized to the defaultValue.

Getting this attribute returns the contents of the [[current value]] slot. See § 1.6.3 Computation of Value for the algorithm for the value that is returned.

Setting this attribute has the effect of assigning the requested value to the [[current value]] slot, and calling the setValueAtTime() method with the current AudioContext's currentTime and [[current value]]. Any exceptions that would be thrown by setValueAtTime() will also be thrown by setting this attribute.

1.6.2. Methods

AudioParam/cancelAndHoldAtTime

In only one current engine.

FirefoxNoneSafariNoneChrome57+
Opera44+Edge79+
Edge (Legacy)NoneIENone
Firefox for AndroidNoneiOS SafariNoneChrome for Android57+Android WebView57+Samsung Internet7.0+Opera Mobile43+

cancelAndHoldAtTime(cancelTime)

This is similar to cancelScheduledValues() in that it cancels all scheduled parameter changes with times greater than or equal to cancelTime. However, in addition, the automation value that would have happened at cancelTime is then proprogated for all future time until other automation events are introduced.

The behavior of the timeline in the face of cancelAndHoldAtTime() when automations are running and can be introduced at any time after calling cancelAndHoldAtTime() and before cancelTime is reached is quite complicated. The behavior of cancelAndHoldAtTime() is therefore specified in the following algorithm.

Let \(t_c\) be the value of cancelTime. Then
  1. Let \(E_1\) be the event (if any) at time \(t_1\) where \(t_1\) is the largest number satisfying \(t_1 \le t_c\).

  2. Let \(E_2\) be the event (if any) at time \(t_2\) where \(t_2\) is the smallest number satisfying \(t_c \lt t_2\).

  3. If \(E_2\) exists:

    1. If \(E_2\) is a linear or exponential ramp,

      1. Effectively rewrite \(E_2\) to be the same kind of ramp ending at time \(t_c\) with an end value that would be the value of the original ramp at time \(t_c\). Graphical representation of calling cancelAndHoldAtTime when linearRampToValueAtTime has been called at this time.

      2. Go to step 5.

    2. Otherwise, go to step 4.

  4. If \(E_1\) exists:

    1. If \(E_1\) is a setTarget event,

      1. Implicitly insert a setValueAtTime event at time \(t_c\) with the value that the setTarget would have at time \(t_c\). Graphical representation of calling cancelAndHoldAtTime when setTargetAtTime has been called at this time

      2. Go to step 5.

    2. If \(E_1\) is a setValueCurve with a start time of \(t_3\) and a duration of \(d\)

      1. If \(t_c \gt t_3 + d\), go to step 5.

      2. Otherwise,

        1. Effectively replace this event with a setValueCurve event with a start time of \(t_3\) and a new duration of \(t_c-t_3\). However, this is not a true replacement; this automation MUST take care to produce the same output as the original, and not one computed using a different duration. (That would cause sampling of the value curve in a slightly different way, producing different results.) Graphical representation of calling cancelAndHoldAtTime when setValueCurve has been called at this time

        2. Go to step 5.

  5. Remove all events with time greater than \(t_c\).

If no events are added, then the automation value after cancelAndHoldAtTime() is the constant value that the original timeline would have had at time \(t_c\).

Arguments for the AudioParam.cancelAndHoldAtTime() method.
Parameter Type Nullable Optional Description
cancelTime double The time after which any previously scheduled parameter changes will be cancelled. It is a time in the same time coordinate system as the AudioContext's currentTime attribute. A RangeError exception MUST be thrown if cancelTime is negative or is not a finite number. If cancelTime is less than currentTime, it is clamped to currentTime.
Return type: AudioParam

AudioParam/cancelScheduledValues

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

cancelScheduledValues(cancelTime)

Cancels all scheduled parameter changes with times greater than or equal to cancelTime. Cancelling a scheduled parameter change means removing the scheduled event from the event list. Any active automations whose automation event time is less than cancelTime are also cancelled, and such cancellations may cause discontinuities because the original value (from before such automation) is restored immediately. Any hold values scheduled by cancelAndHoldAtTime() are also removed if the hold time occurs after cancelTime.

For a setValueCurveAtTime(), let \(T_0\) and \(T_D\) be the corresponding startTime and duration, respectively of this event. Then if cancelTime is in the range \([T_0, T_0 + T_D]\), the event is removed from the timeline.

Arguments for the AudioParam.cancelScheduledValues() method.
Parameter Type Nullable Optional Description
cancelTime double The time after which any previously scheduled parameter changes will be cancelled. It is a time in the same time coordinate system as the AudioContext's currentTime attribute. A RangeError exception MUST be thrown if cancelTime is negative or is not a finite number. If cancelTime is less than currentTime, it is clamped to currentTime.
Return type: AudioParam

AudioParam/exponentialRampToValueAtTime

FirefoxNoneSafari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for AndroidNoneiOS SafariYesChrome for AndroidNoneAndroid WebView37+Samsung Internet1.0+Opera Mobile14+

exponentialRampToValueAtTime(value, endTime)

Schedules an exponential continuous change in parameter value from the previous scheduled parameter value to the given value. Parameters representing filter frequencies and playback rate are best changed exponentially because of the way humans perceive sound.

The value during the time interval \(T_0 \leq t < T_1\) (where \(T_0\) is the time of the previous event and \(T_1\) is the endTime parameter passed into this method) will be calculated as:

$$
  v(t) = V_0 \left(\frac{V_1}{V_0}\right)^\frac{t - T_0}{T_1 - T_0}
$$

where \(V_0\) is the value at the time \(T_0\) and \(V_1\) is the value parameter passed into this method. If \(V_0\) and \(V_1\) have opposite signs or if \(V_0\) is zero, then \(v(t) = V_0\) for \(T_0 \le t \lt T_1\).

This also implies an exponential ramp to 0 is not possible. A good approximation can be achieved using setTargetAtTime() with an appropriately chosen time constant.

If there are no more events after this ExponentialRampToValue event then for \(t \geq T_1\), \(v(t) = V_1\).

If there is no event preceding this event, the exponential ramp behaves as if setValueAtTime(value, currentTime) were called where value is the current value of the attribute and currentTime is the context currentTime at the time exponentialRampToValueAtTime() is called.

If the preceding event is a SetTarget event, \(T_0\) and \(V_0\) are chosen from the current time and value of SetTarget automation. That is, if the SetTarget event has not started, \(T_0\) is the start time of the event, and \(V_0\) is the value just before the SetTarget event starts. In this case, the ExponentialRampToValue event effectively replaces the SetTarget event. If the SetTarget event has already started, \(T_0\) is the current context time, and \(V_0\) is the current SetTarget automation value at time \(T_0\). In both cases, the automation curve is continuous.

Arguments for the AudioParam.exponentialRampToValueAtTime() method.
Parameter Type Nullable Optional Description
value float The value the parameter will exponentially ramp to at the given time. A RangeError exception MUST be thrown if this value is equal to 0.
endTime double The time in the same time coordinate system as the AudioContext's currentTime attribute where the exponential ramp ends. A RangeError exception MUST be thrown if endTime is negative or is not a finite number. If endTime is less than currentTime, it is clamped to currentTime.
Return type: AudioParam

AudioParam/linearRampToValueAtTime

FirefoxNoneSafari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for AndroidNoneiOS Safari?Chrome for AndroidNoneAndroid WebView37+Samsung Internet1.0+Opera Mobile14+

linearRampToValueAtTime(value, endTime)

Schedules a linear continuous change in parameter value from the previous scheduled parameter value to the given value.

The value during the time interval \(T_0 \leq t < T_1\) (where \(T_0\) is the time of the previous event and \(T_1\) is the endTime parameter passed into this method) will be calculated as:

$$
  v(t) = V_0 + (V_1 - V_0) \frac{t - T_0}{T_1 - T_0}
$$

where \(V_0\) is the value at the time \(T_0\) and \(V_1\) is the value parameter passed into this method.

If there are no more events after this LinearRampToValue event then for \(t \geq T_1\), \(v(t) = V_1\).

If there is no event preceding this event, the linear ramp behaves as if setValueAtTime(value, currentTime) were called where value is the current value of the attribute and currentTime is the context currentTime at the time linearRampToValueAtTime() is called.

If the preceding event is a SetTarget event, \(T_0\) and \(V_0\) are chosen from the current time and value of SetTarget automation. That is, if the SetTarget event has not started, \(T_0\) is the start time of the event, and \(V_0\) is the value just before the SetTarget event starts. In this case, the LinearRampToValue event effectively replaces the SetTarget event. If the SetTarget event has already started, \(T_0\) is the current context time, and \(V_0\) is the current SetTarget automation value at time \(T_0\). In both cases, the automation curve is continuous.

Arguments for the AudioParam.linearRampToValueAtTime() method.
Parameter Type Nullable Optional Description
value float The value the parameter will linearly ramp to at the given time.
endTime double The time in the same time coordinate system as the AudioContext's currentTime attribute at which the automation ends. A RangeError exception MUST be thrown if endTime is negative or is not a finite number. If endTime is less than currentTime, it is clamped to currentTime.
Return type: AudioParam

AudioParam/setTargetAtTime

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

setTargetAtTime(target, startTime, timeConstant)

Start exponentially approaching the target value at the given time with a rate having the given time constant. Among other uses, this is useful for implementing the "decay" and "release" portions of an ADSR envelope. Please note that the parameter value does not immediately change to the target value at the given time, but instead gradually changes to the target value.

During the time interval: \(T_0 \leq t\), where \(T_0\) is the startTime parameter:

$$
  v(t) = V_1 + (V_0 - V_1)\, e^{-\left(\frac{t - T_0}{\tau}\right)}
$$

where \(V_0\) is the initial value (the [[current value]] attribute) at \(T_0\) (the startTime parameter), \(V_1\) is equal to the target parameter, and \(\tau\) is the timeConstant parameter.

If a LinearRampToValue or ExponentialRampToValue event follows this event, the behavior is described in linearRampToValueAtTime() or exponentialRampToValueAtTime(), respectively. For all other events, the SetTarget event ends at the time of the next event.

Arguments for the AudioParam.setTargetAtTime() method.
Parameter Type Nullable Optional Description
target float The value the parameter will start changing to at the given time.
startTime double The time at which the exponential approach will begin, in the same time coordinate system as the AudioContext's currentTime attribute. A RangeError exception MUST be thrown if start is negative or is not a finite number. If startTime is less than currentTime, it is clamped to currentTime.
timeConstant float The time-constant value of first-order filter (exponential) approach to the target value. The larger this value is, the slower the transition will be. The value MUST be non-negative or a RangeError exception MUST be thrown. If timeConstant is zero, the output value jumps immediately to the final value. More precisely, timeConstant is the time it takes a first-order linear continuous time-invariant system to reach the value \(1 - 1/e\) (around 63.2%) given a step input response (transition from 0 to 1 value).
Return type: AudioParam

AudioParam/setValueAtTime

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

setValueAtTime(value, startTime)

Schedules a parameter value change at the given time.

If there are no more events after this SetValue event, then for \(t \geq T_0\), \(v(t) = V\), where \(T_0\) is the startTime parameter and \(V\) is the value parameter. In other words, the value will remain constant.

If the next event (having time \(T_1\)) after this SetValue event is not of type LinearRampToValue or ExponentialRampToValue, then, for \(T_0 \leq t < T_1\):

$$
  v(t) = V
$$

In other words, the value will remain constant during this time interval, allowing the creation of "step" functions.

If the next event after this SetValue event is of type LinearRampToValue or ExponentialRampToValue then please see linearRampToValueAtTime() or exponentialRampToValueAtTime(), respectively.

Arguments for the AudioParam.setValueAtTime() method.
Parameter Type Nullable Optional Description
value float The value the parameter will change to at the given time.
startTime double The time in the same time coordinate system as the BaseAudioContext's currentTime attribute at which the parameter changes to the given value. A RangeError exception MUST be thrown if startTime is negative or is not a finite number. If startTime is less than currentTime, it is clamped to currentTime.
Return type: AudioParam

AudioParam/setValueCurveAtTime

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

setValueCurveAtTime(values, startTime, duration)

Sets an array of arbitrary parameter values starting at the given time for the given duration. The number of values will be scaled to fit into the desired duration.

Let \(T_0\) be startTime, \(T_D\) be duration, \(V\) be the values array, and \(N\) be the length of the values array. Then, during the time interval: \(T_0 \le t < T_0 + T_D\), let

$$
  \begin{align*} k &= \left\lfloor \frac{N - 1}{T_D}(t-T_0) \right\rfloor \\
  \end{align*}
$$

Then \(v(t)\) is computed by linearly interpolating between \(V[k]\) and \(V[k+1]\),

After the end of the curve time interval (\(t \ge T_0 + T_D\)), the value will remain constant at the final curve value, until there is another automation event (if any).

An implicit call to setValueAtTime() is made at time \(T_0 + T_D\) with value \(V[N-1]\) so that following automations will start from the end of the setValueCurveAtTime() event.

Arguments for the AudioParam.setValueCurveAtTime() method.
Parameter Type Nullable Optional Description
values sequence<float> A sequence of float values representing a parameter value curve. These values will apply starting at the given time and lasting for the given duration. When this method is called, an internal copy of the curve is created for automation purposes. Subsequent modifications of the contents of the passed-in array therefore have no effect on the AudioParam. An InvalidStateError MUST be thrown if this attribute is a sequence<float> object that has a length less than 2.
startTime double The start time in the same time coordinate system as the AudioContext's currentTime attribute at which the value curve will be applied. A RangeError exception MUST be thrown if startTime is negative or is not a finite number. If startTime is less than currentTime, it is clamped to currentTime.
duration double The amount of time in seconds (after the startTime parameter) where values will be calculated according to the values parameter. A RangeError exception MUST be thrown if duration is not strictly positive or is not a finite number.
Return type: AudioParam

1.6.3. Computation of Value

There are two different kind of AudioParams, simple parameters and compound parameters. Simple parameters (the default) are used on their own to compute the final audio output of an AudioNode. Compound parameters are AudioParams that are used with other AudioParams to compute a value that is then used as an input to compute the output of an AudioNode.

The computedValue is the final value controlling the audio DSP and is computed by the audio rendering thread during each rendering time quantum.

The computation of the value of an AudioParam consists of two parts:

These values MUST be computed as follows:

  1. paramIntrinsicValue will be calculated at each time, which is either the value set directly to the value attribute, or, if there are any automation events with times before or at this time, the value as calculated from these events. If automation events are removed from a given time range, then the paramIntrinsicValue value will remain unchanged and stay at its previous value until either the value attribute is directly set, or automation events are added for the time range.

  2. Set [[current value]] to the value of paramIntrinsicValue at the beginning of this render quantum.

  3. paramComputedValue is the sum of the paramIntrinsicValue value and the value of the input AudioParam buffer. If the sum is NaN, replace the sum with the defaultValue.

  4. If this AudioParam is a compound parameter, compute its final value with other AudioParams.

  5. Set computedValue to paramComputedValue.

The nominal range for a computedValue are the lower and higher values this parameter can effectively have. For simple parameters, the computedValue is clamped to the simple nominal range for this parameter. Compound parameters have their final value clamped to their nominal range after having been computed from the different AudioParam values they are composed of.

When automation methods are used, clamping is still applied. However, the automation is run as if there were no clamping at all. Only when the automation values are to be applied to the output is the clamping done as specified above.

For example, consider a node \(N\) has an AudioParam \(p\) with a nominal range of \([0, 1]\), and following automation sequence
N.p.setValueAtTime(0, 0);
N.p.linearRampToValueAtTime(4, 1);
N.p.linearRampToValueAtTime(0, 2);

The initial slope of the curve is 4, until it reaches the maximum value of 1, at which time, the output is held constant. Finally, near time 2, the slope of the curve is -4. This is illustrated in the graph below where the dashed line indicates what would have happened without clipping, and the solid line indicates the actual expected behavior of the audioparam due to clipping to the nominal range.

AudioParam automation clipping to nominal
An example of clipping of an AudioParam automation from the nominal range.

1.6.4. AudioParam Automation Example

AudioParam automation
An example of parameter automation.
const curveLength = 44100;const curve = new Float32Array(curveLength);for (const i = 0; i < curveLength; ++i)  curve[i] = Math.sin(Math.PI * i / curveLength);const t0 = 0;const t1 = 0.1;const t2 = 0.2;const t3 = 0.3;const t4 = 0.325;const t5 = 0.5;const t6 = 0.6;const t7 = 0.7;const t8 = 1.0;const timeConstant = 0.1;param.setValueAtTime(0.2, t0);param.setValueAtTime(0.3, t1);param.setValueAtTime(0.4, t2);param.linearRampToValueAtTime(1, t3);param.linearRampToValueAtTime(0.8, t4);param.setTargetAtTime(.5, t4, timeConstant);// Compute where the setTargetAtTime will be at time t5 so we can make// the following exponential start at the right point so there’s no// jump discontinuity. From the spec, we have// v(t) = 0.5 + (0.8 - 0.5)*exp(-(t-t4)/timeConstant)// Thus v(t5) = 0.5 + (0.8 - 0.5)*exp(-(t5-t4)/timeConstant)param.setValueAtTime(0.5 + (0.8 - 0.5)*Math.exp(-(t5 - t4)/timeConstant), t5);param.exponentialRampToValueAtTime(0.75, t6);param.exponentialRampToValueAtTime(0.05, t7);param.setValueCurveAtTime(curve, t7, t8 - t7);

1.7. The AudioScheduledSourceNode Interface

AudioScheduledSourceNode

In all current engines.

Firefox53+Safari14+Chrome57+
Opera44+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android53+iOS Safari14+Chrome for Android57+Android WebView57+Samsung Internet7.0+Opera Mobile43+

The interface represents the common features of source nodes such as AudioBufferSourceNode, ConstantSourceNode, and OscillatorNode.

Before a source is started (by calling start(), the source node MUST output silence (0). After a source has been stopped (by calling stop()), the source MUST then output silence (0).

AudioScheduledSourceNode cannot be instantiated directly, but is instead extended by the concrete interfaces for the source nodes.

An AudioScheduledSourceNode is said to be playing when its associated BaseAudioContext's currentTime is greater or equal to the time the AudioScheduledSourceNode is set to start, and less than the time it’s set to stop.

AudioScheduledSourceNodes are created with an internal boolean slot [[source started]], initially set to false.

[Exposed=Window]
interface AudioScheduledSourceNode : AudioNode {
  attribute EventHandler onended;
  undefined start(optional double when = 0);
  undefined stop(optional double when = 0);
};

1.7.1. Attributes

AudioScheduledSourceNode/ended_event

In all current engines.

Firefox25+Safari7+Chrome30+
Opera17+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari7+Chrome for Android30+Android WebView37+Samsung Internet2.0+Opera Mobile18+

AudioScheduledSourceNode/onended

In all current engines.

Firefox25+Safari7+Chrome30+
Opera17+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari7+Chrome for Android30+Android WebView37+Samsung Internet2.0+Opera Mobile18+

onended, of type EventHandler

A property used to set the EventHandler (described in HTML[HTML]) for the ended event that is dispatched for AudioScheduledSourceNode node types. When the source node has stopped playing (as determined by the concrete node), an event of type Event (described in HTML [HTML]) will be dispatched to the event handler.

For all AudioScheduledSourceNodes, the onended event is dispatched when the stop time determined by stop() is reached. For an AudioBufferSourceNode, the event is also dispatched because the duration has been reached or if the entire buffer has been played.

1.7.2. Methods

AudioScheduledSourceNode/start

In all current engines.

Firefox25+Safari6.1+Chrome24+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari7+Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile14+

start(when)

Schedules a sound to playback at an exact time.

When this method is called, execute these steps:
  1. If this AudioScheduledSourceNode internal slot [[source started]] is true, an InvalidStateError exception MUST be thrown.

  2. Check for any errors that must be thrown due to parameter constraints described below. If any exception is thrown during this step, abort those steps.

  3. Set the internal slot [[source started]] on this AudioScheduledSourceNode to true.

  4. Queue a control message to start the AudioScheduledSourceNode, including the parameter values in the message.

  5. Send a control message to the associated AudioContext to start running its rendering thread only when all the following conditions are met:

    1. The context’s [[control thread state]] is "suspended".

    2. The context is allowed to start.

    3. [[suspended by user]] flag is false.

    NOTE: This allows start() to start an AudioContext that would otherwise not be allowed to start.

Arguments for the AudioScheduledSourceNode.start(when) method.
Parameter Type Nullable Optional Description
when double The when parameter describes at what time (in seconds) the sound should start playing. It is in the same time coordinate system as the AudioContext's currentTime attribute. When the signal emitted by the AudioScheduledSourceNode depends on the sound’s start time, the exact value of when is always used without rounding to the nearest sample frame. If 0 is passed in for this value or if the value is less than currentTime, then the sound will start playing immediately. A RangeError exception MUST be thrown if when is negative.
Return type: undefined

AudioScheduledSourceNode/stop

In all current engines.

Firefox25+Safari6.1+Chrome24+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari7+Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile14+

stop(when)

Schedules a sound to stop playback at an exact time. If stop is called again after already having been called, the last invocation will be the only one applied; stop times set by previous calls will not be applied, unless the buffer has already stopped prior to any subsequent calls. If the buffer has already stopped, further calls to stop will have no effect. If a stop time is reached prior to the scheduled start time, the sound will not play.

When this method is called, execute these steps:
  1. If this AudioScheduledSourceNode internal slot [[source started]] is not true, an InvalidStateError exception MUST be thrown.

  2. Check for any errors that must be thrown due to parameter constraints described below.

  3. Queue a control message to stop the AudioScheduledSourceNode, including the parameter values in the message.

If the node is an AudioBufferSourceNode, running a control message to stop the AudioBufferSourceNode means invoking the handleStop() function in the playback algorithm.
Arguments for the AudioScheduledSourceNode.stop(when) method.
Parameter Type Nullable Optional Description
when double The when parameter describes at what time (in seconds) the source should stop playing. It is in the same time coordinate system as the AudioContext's currentTime attribute. If 0 is passed in for this value or if the value is less than currentTime, then the sound will stop playing immediately. A RangeError exception MUST be thrown if when is negative.
Return type: undefined

1.8. The AnalyserNode Interface

This interface represents a node which is able to provide real-time frequency and time-domain analysis information. The audio stream will be passed un-processed from input to output.

Property Value Notes
numberOfInputs 1
numberOfOutputs 1 This output may be left unconnected.
channelCount 2
channelCountMode "max"
channelInterpretation "speakers"
tail-time No

AnalyserNode

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+
[Exposed=Window]
interface AnalyserNode : AudioNode {
  constructor (BaseAudioContext context, optional AnalyserOptions options = {});
  undefined getFloatFrequencyData (Float32Array array);
  undefined getByteFrequencyData (Uint8Array array);
  undefined getFloatTimeDomainData (Float32Array array);
  undefined getByteTimeDomainData (Uint8Array array);
  attribute unsigned long fftSize;
  readonly attribute unsigned long frequencyBinCount;
  attribute double minDecibels;
  attribute double maxDecibels;
  attribute double smoothingTimeConstant;
};

1.8.1. Constructors

AnalyserNode/AnalyserNode

Firefox53+SafariNoneChrome55+
Opera42+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android53+iOS SafariNoneChrome for Android55+Android WebView55+Samsung Internet6.0+Opera Mobile42+

AnalyserNode(context, options)

When the constructor is called with a BaseAudioContext c and an option object option, the user agent MUST initialize the AudioNode this, with context and options as arguments.

Arguments for the AnalyserNode.constructor() method.
Parameter Type Nullable Optional Description
context BaseAudioContext The BaseAudioContext this new AnalyserNode will be associated with.
options AnalyserOptions Optional initial parameter value for this AnalyserNode.

1.8.2. Attributes

AnalyserNode/fftSize

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

fftSize, of type unsigned long

The size of the FFT used for frequency-domain analysis (in sample-frames). This MUST be a power of two in the range 32 to 32768, otherwise an IndexSizeError exception MUST be thrown. The default value is 2048. Note that large FFT sizes can be costly to compute.

If the fftSize is changed to a different value, then all state associated with smoothing of the frequency data (for getByteFrequencyData() and getFloatFrequencyData()) is reset. That is the previous block, \(\hat{X}_{-1}[k]\), used for smoothing over time is set to 0 for all \(k\).

Note that increasing fftSize does mean that the current time-domain data must be expanded to include past frames that it previously did not. This means that the AnalyserNode effectively MUST keep around the last 32768 sample-frames and the current time-domain data is the most recent fftSize sample-frames out of that.

AnalyserNode/frequencyBinCount

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

frequencyBinCount, of type unsigned long, readonly

Half the FFT size.

AnalyserNode/maxDecibels

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

maxDecibels, of type double

maxDecibels is the maximum power value in the scaling range for the FFT analysis data for conversion to unsigned byte values. The default value is -30. If the value of this attribute is set to a value less than or equal to minDecibels, an IndexSizeError exception MUST be thrown.

AnalyserNode/minDecibels

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

minDecibels, of type double

minDecibels is the minimum power value in the scaling range for the FFT analysis data for conversion to unsigned byte values. The default value is -100. If the value of this attribute is set to a value more than or equal to maxDecibels, an IndexSizeError exception MUST be thrown.

AnalyserNode/smoothingTimeConstant

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

smoothingTimeConstant, of type double

A value from 0 -> 1 where 0 represents no time averaging with the last analysis frame. The default value is 0.8. If the value of this attribute is set to a value less than 0 or more than 1, an IndexSizeError exception MUST be thrown.

1.8.3. Methods

AnalyserNode/getByteFrequencyData

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

getByteFrequencyData(array)

Get a reference to the bytes held by the Uint8Array passed as an argument. Copies the current frequency data to those bytes. If the array has fewer elements than the frequencyBinCount, the excess elements will be dropped. If the array has more elements than the frequencyBinCount, the excess elements will be ignored. The most recent fftSize frames are used in computing the frequency data.

If another call to getByteFrequencyData() or getFloatFrequencyData() occurs within the same render quantum as a previous call, the current frequency data is not updated with the same data. Instead, the previously computed data is returned.

The values stored in the unsigned byte array are computed in the following way. Let \(Y[k]\) be the current frequency data as described in FFT windowing and smoothing. Then the byte value, \(b[k]\), is

$$
  b[k] = \left\lfloor
      \frac{255}{\mbox{dB}_{max} - \mbox{dB}_{min}}
      \left(Y[k] - \mbox{dB}_{min}\right)
    \right\rfloor
$$

where \(\mbox{dB}_{min}\) is minDecibels and \(\mbox{dB}_{max}\) is maxDecibels. If \(b[k]\) lies outside the range of 0 to 255, \(b[k]\) is clipped to lie in that range.

Arguments for the AnalyserNode.getByteFrequencyData() method.
Parameter Type Nullable Optional Description
array Uint8Array This parameter is where the frequency-domain analysis data will be copied.
Return type: undefined

AnalyserNode/getByteTimeDomainData

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

getByteTimeDomainData(array)

Get a reference to the bytes held by the Uint8Array passed as an argument. Copies the current time-domain data (waveform data) into those bytes. If the array has fewer elements than the value of fftSize, the excess elements will be dropped. If the array has more elements than fftSize, the excess elements will be ignored. The most recent fftSize frames are used in computing the byte data.

The values stored in the unsigned byte array are computed in the following way. Let \(x[k]\) be the time-domain data. Then the byte value, \(b[k]\), is

$$
  b[k] = \left\lfloor 128(1 + x[k]) \right\rfloor.
$$

If \(b[k]\) lies outside the range 0 to 255, \(b[k]\) is clipped to lie in that range.

Arguments for the AnalyserNode.getByteTimeDomainData() method.
Parameter Type Nullable Optional Description
array Uint8Array This parameter is where the time-domain sample data will be copied.
Return type: undefined

AnalyserNode/getFloatFrequencyData

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

getFloatFrequencyData(array)

Get a reference to the bytes held by the Float32Array passed as an argument. Copies the current frequency data into those bytes. If the array has fewer elements than the frequencyBinCount, the excess elements will be dropped. If the array has more elements than the frequencyBinCount, the excess elements will be ignored. The most recent fftSize frames are used in computing the frequency data.

If another call to getFloatFrequencyData() or getByteFrequencyData() occurs within the same render quantum as a previous call, the current frequency data is not updated with the same data. Instead, the previously computed data is returned.

The frequency data are in dB units.

Arguments for the AnalyserNode.getFloatFrequencyData() method.
Parameter Type Nullable Optional Description
array Float32Array This parameter is where the frequency-domain analysis data will be copied.
Return type: undefined

AnalyserNode/getFloatTimeDomainData

Firefox25+SafariNoneChrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariNoneChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

getFloatTimeDomainData(array)

Get a reference to the bytes held by the Float32Array passed as an argument. Copies the current time-domain data (waveform data) into those bytes. If the array has fewer elements than the value of fftSize, the excess elements will be dropped. If the array has more elements than fftSize, the excess elements will be ignored. The most recent fftSize frames are returned (after downmixing).

Arguments for the AnalyserNode.getFloatTimeDomainData() method.
Parameter Type Nullable Optional Description
array Float32Array This parameter is where the time-domain sample data will be copied.
Return type: undefined

1.8.4. AnalyserOptions

This specifies the options to be used when constructing an AnalyserNode. All members are optional; if not specified, the normal default values are used to construct the node.

dictionary AnalyserOptions : AudioNodeOptions {
  unsigned long fftSize = 2048;
  double maxDecibels = -30;
  double minDecibels = -100;
  double smoothingTimeConstant = 0.8;
};
1.8.4.1. Dictionary AnalyserOptions Members
fftSize, of type unsigned long, defaulting to 2048

The desired initial size of the FFT for frequency-domain analysis.

maxDecibels, of type double, defaulting to -30

The desired initial maximum power in dB for FFT analysis.

minDecibels, of type double, defaulting to -100

The desired initial minimum power in dB for FFT analysis.

smoothingTimeConstant, of type double, defaulting to 0.8

The desired initial smoothing constant for the FFT analysis.

1.8.5. Time-Domain Down-Mixing

When the current time-domain data are computed, the input signal must be down-mixed to mono as if channelCount is 1, channelCountMode is "max" and channelInterpretation is "speakers". This is independent of the settings for the AnalyserNode itself. The most recent fftSize frames are used for the down-mixing operation.

1.8.6. FFT Windowing and Smoothing over Time

When the current frequency data are computed, the following operations are to be performed:

  1. Compute the current time-domain data.

  2. Apply a Blackman window to the time domain input data.

  3. Apply a Fourier transform to the windowed time domain input data to get real and imaginary frequency data.

  4. Smooth over time the frequency domain data.

  5. Convert to dB.

In the following, let \(N\) be the value of the fftSize attribute of this AnalyserNode.

Applying a Blackman window consists in the following operation on the input time domain data. Let \(x[n]\) for \(n = 0, \ldots, N - 1\) be the time domain data. The Blackman window is defined by
$$
\begin{align*}
  \alpha &= \mbox{0.16} \\ a_0 &= \frac{1-\alpha}{2} \\
  a_1 &= \frac{1}{2} \\
  a_2 &= \frac{\alpha}{2} \\
  w[n] &= a_0 - a_1 \cos\frac{2\pi n}{N} + a_2 \cos\frac{4\pi n}{N}, \mbox{ for } n = 0, \ldots, N - 1
\end{align*}
$$

The windowed signal \(\hat{x}[n]\) is

$$
  \hat{x}[n] = x[n] w[n], \mbox{ for } n = 0, \ldots, N - 1
$$
Applying a Fourier transform consists of computing the Fourier transform in the following way. Let \(X[k]\) be the complex frequency domain data and \(\hat{x}[n]\) be the windowed time domain data computed above. Then
$$
  X[k] = \frac{1}{N} \sum_{n = 0}^{N - 1} \hat{x}[n]\, W^{-kn}_{N}
$$

for \(k = 0, \dots, N/2-1\) where \(W_N = e^{2\pi i/N}\).

Smoothing over time frequency data consists in the following operation:

Then the smoothed value, \(\hat{X}[k]\), is computed by

$$
  \hat{X}[k] = \tau\, \hat{X}_{-1}[k] + (1 - \tau)\, \left|X[k]\right|
$$

for \(k = 0, \ldots, N - 1\).

Conversion to dB consists of the following operation, where \(\hat{X}[k]\) is computed in smoothing over time:
$$
  Y[k] = 20\log_{10}\hat{X}[k]
$$

for \(k = 0, \ldots, N-1\).

This array, \(Y[k]\), is copied to the output array for getFloatFrequencyData(). For getByteFrequencyData(), the \(Y[k]\) is clipped to lie between minDecibels and maxDecibels and then scaled to fit in an unsigned byte such that minDecibels is represented by the value 0 and maxDecibels is represented by the value 255.

1.9. The AudioBufferSourceNode Interface

AudioBufferSourceNode/AudioBufferSourceNode

Firefox53+SafariNoneChrome55+
Opera42+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android53+iOS SafariNoneChrome for Android55+Android WebView55+Samsung Internet6.0+Opera Mobile42+

AudioBufferSourceNode

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

This interface represents an audio source from an in-memory audio asset in an AudioBuffer. It is useful for playing audio assets which require a high degree of scheduling flexibility and accuracy. If sample-accurate playback of network- or disk-backed assets is required, an implementer should use AudioWorkletNode to implement playback.

The start() method is used to schedule when sound playback will happen. The start() method may not be issued multiple times. The playback will stop automatically when the buffer’s audio data has been completely played (if the loop attribute is false), or when the stop() method has been called and the specified time has been reached. Please see more details in the start() and stop() descriptions.

Property Value Notes
numberOfInputs 0
numberOfOutputs 1
channelCount 2
channelCountMode "max"
channelInterpretation "speakers"
tail-time No

The number of channels of the output equals the number of channels of the AudioBuffer assigned to the buffer attribute, or is one channel of silence if buffer is null.

In addition, if the buffer has more than one channel, then the AudioBufferSourceNode output must change to a single channel of silence at the beginning of a render quantum after the time at which any one of the following conditions holds:

A playhead position for an AudioBufferSourceNode is defined as any quantity representing a time offset in seconds, relative to the time coordinate of the first sample frame in the buffer. Such values are to be considered independently from the node’s playbackRate and detune parameters. In general, playhead positions may be subsample-accurate and need not refer to exact sample frame positions. They may assume valid values between 0 and the duration of the buffer.

The playbackRate and detune attributes form a compound parameter. They are used together to determine a computedPlaybackRate value:

computedPlaybackRate(t) = playbackRate(t) * pow(2, detune(t) / 1200)

The nominal range for this compound parameter is \((-\infty, \infty)\).

AudioBufferSourceNodes are created with an internal boolean slot [[buffer set]], initially set to false.

[Exposed=Window]
interface AudioBufferSourceNode : AudioScheduledSourceNode {
  constructor (BaseAudioContext context,
               optional AudioBufferSourceOptions options = {});
  attribute AudioBuffer? buffer;
  readonly attribute AudioParam playbackRate;
  readonly attribute AudioParam detune;
  attribute boolean loop;
  attribute double loopStart;
  attribute double loopEnd;
  undefined start (optional double when = 0,
                   optional double offset,
                   optional double duration);
};

1.9.1. Constructors

AudioBufferSourceNode(context, options)

When the constructor is called with a BaseAudioContext c and an option object option, the user agent MUST initialize the AudioNode this, with context and options as arguments.

Arguments for the AudioBufferSourceNode.constructor() method.
Parameter Type Nullable Optional Description
context BaseAudioContext The BaseAudioContext this new AudioBufferSourceNode will be associated with.
options AudioBufferSourceOptions Optional initial parameter value for this AudioBufferSourceNode.

1.9.2. Attributes

AudioBufferSourceNode/buffer

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

buffer, of type AudioBuffer, nullable

Represents the audio asset to be played.

To set the buffer attribute, execute these steps:
  1. Let new buffer be the AudioBuffer or null value to be assigned to buffer.

  2. If new buffer is not null and [[buffer set]] is true, throw an InvalidStateError and abort these steps.

  3. If new buffer is not null, set [[buffer set]] to true.

  4. Assign new buffer to the buffer attribute.

  5. If start() has previously been called on this node, perform the operation acquire the content on buffer.

AudioBufferSourceNode/detune

Firefox40+SafariNoneChrome44+
Opera31+Edge79+
Edge (Legacy)13+IENone
Firefox for Android40+iOS SafariNoneChrome for Android44+Android WebView44+Samsung Internet4.0+Opera Mobile32+

detune, of type AudioParam, readonly

An additional parameter, in cents, to modulate the speed at which is rendered the audio stream. This parameter is a compound parameter with playbackRate to form a computedPlaybackRate.

Parameter Value Notes
defaultValue 0
minValue most-negative-single-float Approximately -3.4028235e38
maxValue most-positive-single-float Approximately 3.4028235e38
automationRate "k-rate" Has automation rate constraints

AudioBufferSourceNode/loop

In all current engines.

Firefox25+Safari6+Chrome15+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

loop, of type boolean

Indicates if the region of audio data designated by loopStart and loopEnd should be played continuously in a loop. The default value is false.

AudioBufferSourceNode/loopEnd

In all current engines.

Firefox25+Safari6+Chrome24+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile14+

loopEnd, of type double

An optional playhead position where looping should end if the loop attribute is true. Its value is exclusive of the content of the loop. Its default value is 0, and it may usefully be set to any value between 0 and the duration of the buffer. If loopEnd is less than or equal to 0, or if loopEnd is greater than the duration of the buffer, looping will end at the end of the buffer.

AudioBufferSourceNode/loopStart

In all current engines.

Firefox25+Safari6+Chrome24+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile14+

loopStart, of type double

An optional playhead position where looping should begin if the loop attribute is true. Its default value is 0, and it may usefully be set to any value between 0 and the duration of the buffer. If loopStart is less than 0, looping will begin at 0. If loopStart is greater than the duration of the buffer, looping will begin at the end of the buffer.

AudioBufferSourceNode/playbackRate

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

playbackRate, of type AudioParam, readonly

The speed at which to render the audio stream. This is a compound parameter with detune to form a computedPlaybackRate.

Parameter Value Notes
defaultValue 1
minValue most-negative-single-float Approximately -3.4028235e38
maxValue most-positive-single-float Approximately 3.4028235e38
automationRate "k-rate" Has automation rate constraints

1.9.3. Methods

AudioBufferSourceNode/start

In all current engines.

Firefox25+Safari6.1+Chrome24+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS Safari7+Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile14+

start(when, offset, duration)

Schedules a sound to playback at an exact time.

When this method is called, execute these steps:
  1. If this AudioBufferSourceNode internal slot [[source started]] is true, an InvalidStateError exception MUST be thrown.

  2. Check for any errors that must be thrown due to parameter constraints described below. If any exception is thrown during this step, abort those steps.

  3. Set the internal slot [[source started]] on this AudioBufferSourceNode to true.

  4. Queue a control message to start the AudioBufferSourceNode, including the parameter values in the message.

  5. Acquire the contents of the buffer if the buffer has been set.

  6. Send a control message to the associated AudioContext to start running its rendering thread only when all the following conditions are met:

    1. The context’s [[control thread state]] is suspended.

    2. The context is allowed to start.

    3. [[suspended by user]] flag is false.

    NOTE: This allows start() to start an AudioContext that would otherwise not be allowed to start.

Running a control message to start the AudioBufferSourceNode means invoking the handleStart() function in the playback algorithm which follows.
Arguments for the AudioBufferSourceNode.start(when, offset, duration) method.
Parameter Type Nullable Optional Description
when double The when parameter describes at what time (in seconds) the sound should start playing. It is in the same time coordinate system as the AudioContext's currentTime attribute. If 0 is passed in for this value or if the value is less than currentTime, then the sound will start playing immediately. A RangeError exception MUST be thrown if when is negative.
offset double The offset parameter supplies a playhead position where playback will begin. If 0 is passed in for this value, then playback will start from the beginning of the buffer. A RangeError exception MUST be thrown if offset is negative. If offset is greater than loopEnd, playbackRate is positive or zero, and loop is true, playback will begin at loopEnd. If offset is greater than loopStart, playbackRate is negative, and loop is true, playback will begin at loopStart. offset is silently clamped to [0, duration], when startTime is reached, where duration is the value of the duration attribute of the AudioBuffer set to the buffer attribute of this AudioBufferSourceNode.
duration double The duration parameter describes the duration of sound to be played, expressed as seconds of total buffer content to be output, including any whole or partial loop iterations. The units of duration are independent of the effects of playbackRate. For example, a duration of 5 seconds with a playback rate of 0.5 will output 5 seconds of buffer content at half speed, producing 10 seconds of audible output. A RangeError exception MUST be thrown if duration is negative.
Return type: undefined

1.9.4. AudioBufferSourceOptions

This specifies options for constructing a AudioBufferSourceNode. All members are optional; if not specified, the normal default is used in constructing the node.

dictionary AudioBufferSourceOptions {
  AudioBuffer? buffer;
  float detune = 0;
  boolean loop = false;
  double loopEnd = 0;
  double loopStart = 0;
  float playbackRate = 1;
};
1.9.4.1. Dictionary AudioBufferSourceOptions Members
buffer, of type AudioBuffer, nullable

The audio asset to be played. This is equivalent to assigning buffer to the buffer attribute of the AudioBufferSourceNode.

detune, of type float, defaulting to 0

The initial value for the detune AudioParam.

loop, of type boolean, defaulting to false

The initial value for the loop attribute.

loopEnd, of type double, defaulting to 0

The initial value for the loopEnd attribute.

loopStart, of type double, defaulting to 0

The initial value for the loopStart attribute.

playbackRate, of type float, defaulting to 1

The initial value for the playbackRate AudioParam.

1.9.5. Looping

This section is non-normative. Please see the playback algorithm for normative requirements.

Setting the loop attribute to true causes playback of the region of the buffer defined by the endpoints loopStart and loopEnd to continue indefinitely, once any part of the looped region has been played. While loop remains true, looped playback will continue until one of the following occurs:

The body of the loop is considered to occupy a region from loopStart up to, but not including, loopEnd. The direction of playback of the looped region respects the sign of the node’s playback rate. For positive playback rates, looping occurs from loopStart to loopEnd; for negative rates, looping occurs from loopEnd to loopStart.

Looping does not affect the interpretation of the offset argument of start(). Playback always starts at the requested offset, and looping only begins once the body of the loop is encountered during playback.

The effective loop start and end points are required to lie within the range of zero and the buffer duration, as specified in the algorithm below. loopEnd is further constrained to be at or after loopStart. If any of these constraints are violated, the loop is considered to include the entire buffer contents.

Loop endpoints have subsample accuracy. When endpoints do not fall on exact sample frame offsets, or when the playback rate is not equal to 1, playback of the loop is interpolated to splice the beginning and end of the loop together just as if the looped audio occurred in sequential, non-looped regions of the buffer.

Loop-related properties may be varied during playback of the buffer, and in general take effect on the next rendering quantum. The exact results are defined by the normative playback algorithm which follows.

The default values of the loopStart and loopEnd attributes are both 0. Since a loopEnd value of zero is equivalent to the length of the buffer, the default endpoints cause the entire buffer to be included in the loop.

Note that the values of the loop endpoints are expressed as time offsets in terms of the sample rate of the buffer, meaning that these values are independent of the node’s playbackRate parameter which can vary dynamically during the course of playback.

1.9.6. Playback of AudioBuffer Contents

This normative section specifies the playback of the contents of the buffer, accounting for the fact that playback is influenced by the following factors working in combination:

The algorithm to be followed internally to generate output from an AudioBufferSourceNode conforms to the following principles:

The description of the algorithm is as follows:

let buffer; // AudioBuffer employed by this nodelet context; // AudioContext employed by this node// The following variables capture attribute and AudioParam values for the node.// They are updated on a k-rate basis, prior to each invocation of process().let loop;let detune;let loopStart;let loopEnd;let playbackRate;// Variables for the node’s playback parameterslet start = 0, offset = 0, duration = Infinity; // Set by start()let stop = Infinity; // Set by stop()// Variables for tracking node’s playback statelet bufferTime = 0, started = false, enteredLoop = false;let bufferTimeElapsed = 0;let dt = 1 / context.sampleRate;// Handle invocation of start method callfunction handleStart(when, pos, dur) {  if (arguments.length >= 1) {    start = when;  }  offset = pos;  if (arguments.length >= 3) {    duration = dur;  }}// Handle invocation of stop method callfunction handleStop(when) {  if (arguments.length >= 1) {    stop = when;  } else {    stop = context.currentTime;  }}// Interpolate a multi-channel signal value for some sample frame.// Returns an array of signal values.function playbackSignal(position) {  /*    This function provides the playback signal function for buffer, which is a    function that maps from a playhead position to a set of output signal    values, one for each output channel. If |position| corresponds to the    location of an exact sample frame in the buffer, this function returns    that frame. Otherwise, its return value is determined by a UA-supplied    algorithm that interpolates sample frames in the neighborhood of    |position|.    If |position| is greater than or equal to |loopEnd| and there is no subsequent    sample frame in buffer, then interpolation should be based on the sequence    of subsequent frames beginning at |loopStart|.   */   ...}// Generate a single render quantum of audio to be placed// in the channel arrays defined by output. Returns an array// of |numberOfFrames| sample frames to be output.function process(numberOfFrames) {  let currentTime = context.currentTime; // context time of next rendered frame  const output = []; // accumulates rendered sample frames  // Combine the two k-rate parameters affecting playback rate  const computedPlaybackRate = playbackRate * Math.pow(2, detune / 1200);  // Determine loop endpoints as applicable  let actualLoopStart, actualLoopEnd;  if (loop && buffer != null) {    if (loopStart >= 0 && loopEnd > 0 && loopStart < loopEnd) {      actualLoopStart = loopStart;      actualLoopEnd = Math.min(loopEnd, buffer.duration);    } else {      actualLoopStart = 0;      actualLoopEnd = buffer.duration;    }  } else {    // If the loop flag is false, remove any record of the loop having been entered    enteredLoop = false;  }  // Handle null buffer case  if (buffer == null) {    stop = currentTime; // force zero output for all time  }  // Render each sample frame in the quantum  for (let index = 0; index < numberOfFrames; index++) {    // Check that currentTime and bufferTimeElapsed are    // within allowable range for playback    if (currentTime < start || currentTime >= stop || bufferTimeElapsed >= duration) {      output.push(0); // this sample frame is silent      currentTime += dt;      continue;    }    if (!started) {      // Take note that buffer has started playing and get initial      // playhead position.      if (loop && computedPlaybackRate >= 0 && offset >= actualLoopEnd) {        offset = actualLoopEnd;      }      if (computedPlaybackRate < 0 && loop && offset < actualLoopStart) {        offset = actualLoopStart;      }      bufferTime = offset;      started = true;    }    // Handle loop-related calculations    if (loop) {      // Determine if looped portion has been entered for the first time      if (!enteredLoop) {        if (offset < actualLoopEnd && bufferTime >= actualLoopStart) {          // playback began before or within loop, and playhead is          // now past loop start          enteredLoop = true;        }        if (offset >= actualLoopEnd && bufferTime < actualLoopEnd) {          // playback began after loop, and playhead is now prior          // to the loop end          enteredLoop = true;        }      }      // Wrap loop iterations as needed. Note that enteredLoop      // may become true inside the preceding conditional.      if (enteredLoop) {        while (bufferTime >= actualLoopEnd) {          bufferTime -= actualLoopEnd - actualLoopStart;        }        while (bufferTime < actualLoopStart) {          bufferTime += actualLoopEnd - actualLoopStart;        }      }    }    if (bufferTime >= 0 && bufferTime < buffer.duration) {      output.push(playbackSignal(bufferTime));    } else {      output.push(0); // past end of buffer, so output silent frame    }    bufferTime += dt * computedPlaybackRate;    bufferTimeElapsed += dt * computedPlaybackRate;    currentTime += dt;  } // End of render quantum loop  if (currentTime >= stop) {    // End playback state of this node.  No further invocations of process()    // will occur.  Schedule a change to set the number of output channels to 1.  }  return output;}

The following non-normative figures illustrate the behavior of the algorithm in assorted key scenarios. Dynamic resampling of the buffer is not considered, but as long as the times of loop positions are not changed this does not materially affect the resulting playback. In all figures, the following conventions apply:

This figure illustrates basic playback of a buffer, with a simple loop that ends after the last sample frame in the buffer:

AudioBufferSourceNode basic playback
AudioBufferSourceNode basic playback

This figure illustrates playbackRate interpolation, showing half-speed playback of buffer contents in which every other output sample frame is interpolated. Of particular note is the last sample frame in the looped output, which is interpolated using the loop start point:

AudioBufferSourceNode playbackRate interpolation
AudioBufferSourceNode playbackRate interpolation

This figure illustrates sample rate interpolation, showing playback of a buffer whose sample rate is 50% of the context sample rate, resulting in a computed playback rate of 0.5 that corrects for the difference in sample rate between the buffer and the context. The resulting output is the same as the preceding example, but for different reasons.

AudioBufferSourceNode sample rate interpolation
AudioBufferSourceNode sample rate interpolation.

This figure illustrates subsample offset playback, in which the offset within the buffer begins at exactly half a sample frame. Consequently, every output frame is interpolated:

AudioBufferSourceNode subsample offset playback
AudioBufferSourceNode subsample offset playback

This figure illustrates subsample loop playback, showing how fractional frame offsets in the loop endpoints map to interpolated data points in the buffer that respect these offsets as if they were references to exact sample frames:

AudioBufferSourceNode subsample loop playback
AudioBufferSourceNode subsample loop playback

1.10. The AudioDestinationNode Interface

AudioDestinationNode

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

This is an AudioNode representing the final audio destination and is what the user will ultimately hear. It can often be considered as an audio output device which is connected to speakers. All rendered audio to be heard will be routed to this node, a "terminal" node in the AudioContext's routing graph. There is only a single AudioDestinationNode per AudioContext, provided through the destination attribute of AudioContext.

The output of a AudioDestinationNode is produced by summing its input, allowing to capture the output of an AudioContext into, for example, a MediaStreamAudioDestinationNode, or a MediaRecorder (described in [mediastream-recording]).

The AudioDestinationNode can be either the destination of an AudioContext or OfflineAudioContext, and the channel properties depend on what the context is.

For an AudioContext, the defaults are

Property Value Notes
numberOfInputs 1
numberOfOutputs 1
channelCount 2
channelCountMode "explicit"
channelInterpretation "speakers"
tail-time No

The channelCount can be set to any value less than or equal to maxChannelCount. An IndexSizeError exception MUST be thrown if this value is not within the valid range. Giving a concrete example, if the audio hardware supports 8-channel output, then we may set channelCount to 8, and render 8 channels of output.

For an OfflineAudioContext, the defaults are

Property Value Notes
numberOfInputs 1
numberOfOutputs 1
channelCount numberOfChannels
channelCountMode "explicit"
channelInterpretation "speakers"
tail-time No

where numberOfChannels is the number of channels specified when constructing the OfflineAudioContext. This value may not be changed; a NotSupportedError exception MUST be thrown if channelCount is changed to a different value.

[Exposed=Window]
interface AudioDestinationNode : AudioNode {
  readonly attribute unsigned long maxChannelCount;
};

1.10.1. Attributes

AudioDestinationNode/maxChannelCount

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

maxChannelCount, of type unsigned long, readonly

The maximum number of channels that the channelCount attribute can be set to. An AudioDestinationNode representing the audio hardware end-point (the normal case) can potentially output more than 2 channels of audio if the audio hardware is multi-channel. maxChannelCount is the maximum number of channels that this hardware is capable of supporting.

1.11. The AudioListener Interface

This interface represents the position and orientation of the person listening to the audio scene. All PannerNode objects spatialize in relation to the BaseAudioContext's listener. See § 6 Spatialization/Panning for more details about spatialization.

The positionX, positionY, and positionZ parameters represent the location of the listener in 3D Cartesian coordinate space. PannerNode objects use this position relative to individual audio sources for spatialization.

The forwardX, forwardY, and forwardZ parameters represent a direction vector in 3D space. Both a forward vector and an up vector are used to determine the orientation of the listener. In simple human terms, the forward vector represents which direction the person’s nose is pointing. The up vector represents the direction the top of a person’s head is pointing. These two vectors are expected to be linearly independent. For normative requirements of how these values are to be interpreted, see the § 6 Spatialization/Panning section.

AudioListener

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+
[Exposed=Window]
interface AudioListener {
  readonly attribute AudioParam positionX;
  readonly attribute AudioParam positionY;
  readonly attribute AudioParam positionZ;
  readonly attribute AudioParam forwardX;
  readonly attribute AudioParam forwardY;
  readonly attribute AudioParam forwardZ;
  readonly attribute AudioParam upX;
  readonly attribute AudioParam upY;
  readonly attribute AudioParam upZ;
  undefined setPosition (float x, float y, float z);
  undefined setOrientation (float x, float y, float z, float xUp, float yUp, float zUp);
};

1.11.1. Attributes

AudioListener/forwardX

In only one current engine.

FirefoxNoneSafariNoneChrome52+
Opera39+Edge79+
Edge (Legacy)NoneIENone
Firefox for AndroidNoneiOS SafariNoneChrome for Android52+Android WebView52+Samsung Internet6.0+Opera Mobile41+

forwardX, of type AudioParam, readonly

Sets the x coordinate component of the forward direction the listener is pointing in 3D Cartesian coordinate space.

Parameter Value Notes
defaultValue 0
minValue most-negative-single-float Approximately -3.4028235e38
maxValue most-positive-single-float Approximately 3.4028235e38
automationRate "a-rate"

AudioListener/forwardY

In only one current engine.

FirefoxNoneSafariNoneChrome52+
Opera39+Edge79+
Edge (Legacy)NoneIENone
Firefox for AndroidNoneiOS SafariNoneChrome for Android52+Android WebView52+Samsung Internet6.0+Opera Mobile41+

forwardY, of type AudioParam, readonly

Sets the y coordinate component of the forward direction the listener is pointing in 3D Cartesian coordinate space.

Parameter Value Notes
defaultValue 0
minValue most-negative-single-float Approximately -3.4028235e38
maxValue most-positive-single-float Approximately 3.4028235e38
automationRate "a-rate"

AudioListener/forwardZ

In only one current engine.

FirefoxNoneSafariNoneChrome52+
Opera39+Edge79+
Edge (Legacy)NoneIENone
Firefox for AndroidNoneiOS SafariNoneChrome for Android52+Android WebView52+Samsung Internet6.0+Opera Mobile41+

forwardZ, of type AudioParam, readonly

Sets the z coordinate component of the forward direction the listener is pointing in 3D Cartesian coordinate space.

Parameter Value Notes
defaultValue -1
minValue most-negative-single-float Approximately -3.4028235e38
maxValue most-positive-single-float Approximately 3.4028235e38
automationRate "a-rate"

AudioListener/positionX

In only one current engine.

FirefoxNoneSafariNoneChrome52+
Opera39+Edge79+
Edge (Legacy)NoneIENone
Firefox for AndroidNoneiOS SafariNoneChrome for Android52+Android WebView52+Samsung Internet6.0+Opera Mobile41+

positionX, of type AudioParam, readonly

Sets the x coordinate position of the audio listener in a 3D Cartesian coordinate space.

Parameter Value Notes
defaultValue 0
minValue most-negative-single-float Approximately -3.4028235e38
maxValue most-positive-single-float Approximately 3.4028235e38
automationRate "a-rate"

AudioListener/positionY

In only one current engine.

FirefoxNoneSafariNoneChrome52+
Opera39+Edge79+
Edge (Legacy)NoneIENone
Firefox for AndroidNoneiOS SafariNoneChrome for Android52+Android WebView52+Samsung Internet6.0+Opera Mobile41+

positionY, of type AudioParam, readonly

Sets the y coordinate position of the audio listener in a 3D Cartesian coordinate space.

Parameter Value Notes
defaultValue 0
minValue most-negative-single-float Approximately -3.4028235e38
maxValue most-positive-single-float Approximately 3.4028235e38
automationRate "a-rate"

AudioListener/positionZ

In only one current engine.

FirefoxNoneSafariNoneChrome52+
Opera39+Edge79+
Edge (Legacy)NoneIENone
Firefox for AndroidNoneiOS SafariNoneChrome for Android52+Android WebView52+Samsung Internet6.0+Opera Mobile41+

positionZ, of type AudioParam, readonly

Sets the z coordinate position of the audio listener in a 3D Cartesian coordinate space.

Parameter Value Notes
defaultValue 0
minValue most-negative-single-float Approximately -3.4028235e38
maxValue most-positive-single-float Approximately 3.4028235e38
automationRate "a-rate"

AudioListener/upX

In only one current engine.

FirefoxNoneSafariNoneChrome52+
Opera39+Edge79+
Edge (Legacy)NoneIENone
Firefox for AndroidNoneiOS SafariNoneChrome for Android52+Android WebView52+Samsung Internet6.0+Opera Mobile41+

upX, of type AudioParam, readonly

Sets the x coordinate component of the up direction the listener is pointing in 3D Cartesian coordinate space.

Parameter Value Notes
defaultValue 0
minValue most-negative-single-float Approximately -3.4028235e38
maxValue most-positive-single-float Approximately 3.4028235e38
automationRate "a-rate"

AudioListener/upY

In only one current engine.

FirefoxNoneSafariNoneChrome52+
Opera39+Edge79+
Edge (Legacy)NoneIENone
Firefox for AndroidNoneiOS SafariNoneChrome for Android52+Android WebView52+Samsung Internet6.0+Opera Mobile41+

upY, of type AudioParam, readonly

Sets the y coordinate component of the up direction the listener is pointing in 3D Cartesian coordinate space.

Parameter Value Notes
defaultValue 1
minValue most-negative-single-float Approximately -3.4028235e38
maxValue most-positive-single-float Approximately 3.4028235e38
automationRate "a-rate"

AudioListener/upZ

In only one current engine.

FirefoxNoneSafariNoneChrome52+
Opera39+Edge79+
Edge (Legacy)NoneIENone
Firefox for AndroidNoneiOS SafariNoneChrome for Android52+Android WebView52+Samsung Internet6.0+Opera Mobile41+

upZ, of type AudioParam, readonly

Sets the z coordinate component of the up direction the listener is pointing in 3D Cartesian coordinate space.

Parameter Value Notes
defaultValue 0
minValue most-negative-single-float Approximately -3.4028235e38
maxValue most-positive-single-float Approximately 3.4028235e38
automationRate "a-rate"

1.11.2. Methods

setOrientation(x, y, z, xUp, yUp, zUp)

This method is DEPRECATED. It is equivalent to setting forwardX.value, forwardY.value, forwardZ.value, upX.value, upY.value, and upZ.value directly with the given x, y, z, xUp, yUp, and zUp values, respectively.

Consequently, if any of the forwardX, forwardY, forwardZ, upX, upY and upZ AudioParams have an automation curve set using setValueCurveAtTime() at the time this method is called, a NotSupportedError MUST be thrown.

setOrientation() describes which direction the listener is pointing in the 3D cartesian coordinate space. Both a forward vector and an up vector are provided. In simple human terms, the forward vector represents which direction the person’s nose is pointing. The up vector represents the direction the top of a person’s head is pointing. These two vectors are expected to be linearly independent. For normative requirements of how these values are to be interpreted, see the § 6 Spatialization/Panning.

The x, y, and z parameters represent a forward direction vector in 3D space, with the default value being (0,0,-1).

The xUp, yUp, and zUp parameters represent an up direction vector in 3D space, with the default value being (0,1,0).

Arguments for the AudioListener.setOrientation() method.
Parameter Type Nullable Optional Description
x float forward x direction fo the AudioListener
y float forward y direction fo the AudioListener
z float forward z direction fo the AudioListener
xUp float up x direction fo the AudioListener
yUp float up y direction fo the AudioListener
zUp float up z direction fo the AudioListener
Return type: undefined
setPosition(x, y, z)

This method is DEPRECATED. It is equivalent to setting positionX.value, positionY.value, and positionZ.value directly with the given x, y, and z values, respectively.

Consequently, any of the positionX, positionY, and positionZ AudioParams for this AudioListener have an automation curve set using setValueCurveAtTime() at the time this method is called, a NotSupportedError MUST be thrown.

setPosition() sets the position of the listener in a 3D cartesian coordinate space. PannerNode objects use this position relative to individual audio sources for spatialization.

The x, y, and z parameters represent the coordinates in 3D space.

The default value is (0,0,0).

Arguments for the AudioListener.setPosition() method.
Parameter Type Nullable Optional Description
x float x-coordinate of the position of the AudioListener
y float y-coordinate of the position of the AudioListener
z float z-coordinate of the position of the AudioListener

1.11.3. Processing

Because AudioListener's parameters can be connected with AudioNodes and they can also affect the output of PannerNodes in the same graph, the node ordering algorithm should take the AudioListener into consideration when computing the order of processing. For this reason, all the PannerNodes in the graph have the AudioListener as input.

1.12. The AudioProcessingEvent Interface - DEPRECATED

This is an Event object which is dispatched to ScriptProcessorNode nodes. It will be removed when the ScriptProcessorNode is removed, as the replacement AudioWorkletNode uses a different approach.

The event handler processes audio from the input (if any) by accessing the audio data from the inputBuffer attribute. The audio data which is the result of the processing (or the synthesized data if there are no inputs) is then placed into the outputBuffer.

[Exposed=Window]
interface AudioProcessingEvent : Event {
  constructor (DOMString type, AudioProcessingEventInit eventInitDict);
  readonly attribute double playbackTime;
  readonly attribute AudioBuffer inputBuffer;
  readonly attribute AudioBuffer outputBuffer;
};

1.12.1. Attributes

inputBuffer, of type AudioBuffer, readonly

An AudioBuffer containing the input audio data. It will have a number of channels equal to the numberOfInputChannels parameter of the createScriptProcessor() method. This AudioBuffer is only valid while in the scope of the onaudioprocess function. Its values will be meaningless outside of this scope.

outputBuffer, of type AudioBuffer, readonly

An AudioBuffer where the output audio data MUST be written. It will have a number of channels equal to the numberOfOutputChannels parameter of the createScriptProcessor() method. Script code within the scope of the onaudioprocess function is expected to modify the Float32Array arrays representing channel data in this AudioBuffer. Any script modifications to this AudioBuffer outside of this scope will not produce any audible effects.

playbackTime, of type double, readonly

The time when the audio will be played in the same time coordinate system as the AudioContext's currentTime.

1.12.2. AudioProcessingEventInit

dictionary AudioProcessingEventInit : EventInit {
  required double playbackTime;
  required AudioBuffer inputBuffer;
  required AudioBuffer outputBuffer;
};
1.12.2.1. Dictionary AudioProcessingEventInit Members
inputBuffer, of type AudioBuffer

Value to be assigned to the inputBuffer attribute of the event.

outputBuffer, of type AudioBuffer

Value to be assigned to the outputBuffer attribute of the event.

playbackTime, of type double

Value to be assigned to the playbackTime attribute of the event.

1.13. The BiquadFilterNode Interface

BiquadFilterNode is an AudioNode processor implementing very common low-order filters.

Low-order filters are the building blocks of basic tone controls (bass, mid, treble), graphic equalizers, and more advanced filters. Multiple BiquadFilterNode filters can be combined to form more complex filters. The filter parameters such as frequency can be changed over time for filter sweeps, etc. Each BiquadFilterNode can be configured as one of a number of common filter types as shown in the IDL below. The default filter type is "lowpass".

Both frequency and detune form a compound parameter and are both a-rate. They are used together to determine a computedFrequency value:

computedFrequency(t) = frequency(t) * pow(2, detune(t) / 1200)

The nominal range for this compound parameter is [0, Nyquist frequency].

Property Value Notes
numberOfInputs 1
numberOfOutputs 1
channelCount 2
channelCountMode "max"
channelInterpretation "speakers"
tail-time Yes Continues to output non-silent audio with zero input. Since this is an IIR filter, the filter produces non-zero input forever, but in practice, this can be limited after some finite time where the output is sufficiently close to zero. The actual time depends on the filter coefficients.

The number of channels of the output always equals the number of channels of the input.

enum BiquadFilterType {
  "lowpass",
  "highpass",
  "bandpass",
  "lowshelf",
  "highshelf",
  "peaking",
  "notch",
  "allpass"
};
Enumeration description
"lowpass" A lowpass filter allows frequencies below the cutoff frequency to pass through and attenuates frequencies above the cutoff. It implements a standard second-order resonant lowpass filter with 12dB/octave rolloff.
frequency

The cutoff frequency

Q

Controls how peaked the response will be at the cutoff frequency. A large value makes the response more peaked.

gain

Not used in this filter type

"highpass" A highpass filter is the opposite of a lowpass filter. Frequencies above the cutoff frequency are passed through, but frequencies below the cutoff are attenuated. It implements a standard second-order resonant highpass filter with 12dB/octave rolloff.
frequency

The cutoff frequency below which the frequencies are attenuated

Q

Controls how peaked the response will be at the cutoff frequency. A large value makes the response more peaked.

gain

Not used in this filter type

"bandpass" A bandpass filter allows a range of frequencies to pass through and attenuates the frequencies below and above this frequency range. It implements a second-order bandpass filter.
frequency

The center of the frequency band

Q

Controls the width of the band. The width becomes narrower as the Q value increases.

gain

Not used in this filter type

"lowshelf" The lowshelf filter allows all frequencies through, but adds a boost (or attenuation) to the lower frequencies. It implements a second-order lowshelf filter.
frequency

The upper limit of the frequences where the boost (or attenuation) is applied.

Q

Not used in this filter type.

gain

The boost, in dB, to be applied. If the value is negative, the frequencies are attenuated.

"highshelf" The highshelf filter is the opposite of the lowshelf filter and allows all frequencies through, but adds a boost to the higher frequencies. It implements a second-order highshelf filter
frequency

The lower limit of the frequences where the boost (or attenuation) is applied.

Q

Not used in this filter type.

gain

The boost, in dB, to be applied. If the value is negative, the frequencies are attenuated.

"peaking" The peaking filter allows all frequencies through, but adds a boost (or attenuation) to a range of frequencies.
frequency

The center frequency of where the boost is applied.

Q

Controls the width of the band of frequencies that are boosted. A large value implies a narrow width.

gain

The boost, in dB, to be applied. If the value is negative, the frequencies are attenuated.

"notch" The notch filter (also known as a band-stop or band-rejection filter) is the opposite of a bandpass filter. It allows all frequencies through, except for a set of frequencies.
frequency

The center frequency of where the notch is applied.

Q

Controls the width of the band of frequencies that are attenuated. A large value implies a narrow width.

gain

Not used in this filter type.

"allpass" An allpass filter allows all frequencies through, but changes the phase relationship between the various frequencies. It implements a second-order allpass filter
frequency

The frequency where the center of the phase transition occurs. Viewed another way, this is the frequency with maximal group delay.

Q

Controls how sharp the phase transition is at the center frequency. A larger value implies a sharper transition and a larger group delay.

gain

Not used in this filter type.

All attributes of the BiquadFilterNode are a-rate AudioParams.

BiquadFilterNode/BiquadFilterNode

Firefox53+SafariNoneChrome55+
Opera42+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android53+iOS SafariNoneChrome for Android55+Android WebView55+Samsung Internet6.0+Opera Mobile42+

BiquadFilterNode

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+
[Exposed=Window]
interface BiquadFilterNode : AudioNode {
  constructor (BaseAudioContext context, optional BiquadFilterOptions options = {});
  attribute BiquadFilterType type;
  readonly attribute AudioParam frequency;
  readonly attribute AudioParam detune;
  readonly attribute AudioParam Q;
  readonly attribute AudioParam gain;
  undefined getFrequencyResponse (Float32Array frequencyHz,
                                  Float32Array magResponse,
                                  Float32Array phaseResponse);
};

1.13.1. Constructors

BiquadFilterNode(context, options)

When the constructor is called with a BaseAudioContext c and an option object option, the user agent MUST initialize the AudioNode this, with context and options as arguments.

Arguments for the BiquadFilterNode.constructor() method.
Parameter Type Nullable Optional Description
context BaseAudioContext The BaseAudioContext this new BiquadFilterNode will be associated with.
options BiquadFilterOptions Optional initial parameter value for this BiquadFilterNode.

1.13.2. Attributes

BiquadFilterNode/Q

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

Q, of type AudioParam, readonly

The Q factor of the filter.

For lowpass and highpass filters the Q value is interpreted to be in dB. For these filters the nominal range is \([-Q_{lim}, Q_{lim}]\) where \(Q_{lim}\) is the largest value for which \(10^{Q/20}\) does not overflow. This is approximately \(770.63678\).

For the bandpass, notch, allpass, and peaking filters, this value is a linear value. The value is related to the bandwidth of the filter and hence should be a positive value. The nominal range is \([0, 3.4028235e38]\), the upper limit being the most-positive-single-float.

This is not used for the lowshelf and highshelf filters.

Parameter Value Notes
defaultValue 1
minValue most-negative-single-float Approximately -3.4028235e38, but see above for the actual limits for different filters
maxValue most-positive-single-float Approximately 3.4028235e38, but see above for the actual limits for different filters
automationRate "a-rate"

BiquadFilterNode/detune

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

detune, of type AudioParam, readonly

A detune value, in cents, for the frequency. It forms a compound parameter with frequency to form the computedFrequency.

Parameter Value Notes
defaultValue 0
minValue \(\approx -153600\)
maxValue \(\approx 153600\) This value is approximately \(1200\ \log_2 \mathrm{FLT\_MAX}\) where FLT_MAX is the largest float value.
automationRate "a-rate"

BiquadFilterNode/frequency

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

frequency, of type AudioParam, readonly

The frequency at which the BiquadFilterNode will operate, in Hz. It forms a compound parameter with detune to form the computedFrequency.

BiquadFilterNode/gain

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

gain, of type AudioParam, readonly

The gain of the filter. Its value is in dB units. The gain is only used for lowshelf, highshelf, and peaking filters.

Parameter Value Notes
defaultValue 0
minValue most-negative-single-float Approximately -3.4028235e38
maxValue \(\approx 1541\) This value is approximately \(40\ \log_{10} \mathrm{FLT\_MAX}\) where FLT_MAX is the largest float value.
automationRate "a-rate"

BiquadFilterNode/type

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

type, of type BiquadFilterType

The type of this BiquadFilterNode. Its default value is "lowpass". The exact meaning of the other parameters depend on the value of the type attribute.

1.13.3. Methods

BiquadFilterNode/getFrequencyResponse

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

getFrequencyResponse(frequencyHz, magResponse, phaseResponse)

Given the [[current value]] from each of the filter parameters, synchronously calculates the frequency response for the specified frequencies. The three parameters MUST be Float32Arrays of the same length, or an InvalidAccessError MUST be thrown.

The frequency response returned MUST be computed with the AudioParam sampled for the current processing block.

Arguments for the BiquadFilterNode.getFrequencyResponse() method.
Parameter Type Nullable Optional Description
frequencyHz Float32Array This parameter specifies an array of frequencies, in Hz, at which the response values will be calculated.
magResponse Float32Array This parameter specifies an output array receiving the linear magnitude response values. If a value in the frequencyHz parameter is not within [0, sampleRate/2], where sampleRate is the value of the sampleRate property of the AudioContext, the corresponding value at the same index of the magResponse array MUST be NaN.
phaseResponse Float32Array This parameter specifies an output array receiving the phase response values in radians. If a value in the frequencyHz parameter is not within [0; sampleRate/2], where sampleRate is the value of the sampleRate property of the AudioContext, the corresponding value at the same index of the phaseResponse array MUST be NaN.
Return type: undefined

1.13.4. BiquadFilterOptions

This specifies the options to be used when constructing a BiquadFilterNode. All members are optional; if not specified, the normal default values are used to construct the node.

dictionary BiquadFilterOptions : AudioNodeOptions {
  BiquadFilterType type = "lowpass";
  float Q = 1;
  float detune = 0;
  float frequency = 350;
  float gain = 0;
};
1.13.4.1. Dictionary BiquadFilterOptions Members
Q, of type float, defaulting to 1

The desired initial value for Q.

detune, of type float, defaulting to 0

The desired initial value for detune.

frequency, of type float, defaulting to 350

The desired initial value for frequency.

gain, of type float, defaulting to 0

The desired initial value for gain.

type, of type BiquadFilterType, defaulting to "lowpass"

The desired initial type of the filter.

1.13.5. Filters Characteristics

There are multiple ways of implementing the type of filters available through the BiquadFilterNode each having very different characteristics. The formulas in this section describe the filters that a conforming implementation MUST implement, as they determine the characteristics of the different filter types. They are inspired by formulas found in the Audio EQ Cookbook.

The BiquadFilterNode processes audio with a transfer function of

$$
 H(z) = \frac{\frac{b_0}{a_0} + \frac{b_1}{a_0}z^{-1} + \frac{b_2}{a_0}z^{-2}}
                                          {1+\frac{a_1}{a_0}z^{-1}+\frac{a_2}{a_0}z^{-2}}
$$

which is equivalent to a time-domain equation of:

$$
a_0 y(n) + a_1 y(n-1) + a_2 y(n-2) =
  b_0 x(n) + b_1 x(n-1) + b_2 x(n-2)
$$

The initial filter state is 0.

Note: While fixed filters are stable, it is possible to create unstable biquad filters using automations of AudioParams. It is the developers responsibility to manage this.

Note: The UA may produce a warning to notify the user that NaN values have occurred in the filter state. This is usually indicative of an unstable filter.

The coefficients in the transfer function above are different for each node type. The following intermediate variables are necessary for their computation, based on the computedValue of the AudioParams of the BiquadFilterNode.

The six coefficients (\(b_0, b_1, b_2, a_0, a_1, a_2\)) for each filter type, are:

"lowpass"
$$
  \begin{align*}
    b_0 &= \frac{1 - \cos\omega_0}{2} \\
    b_1 &= 1 - \cos\omega_0 \\
    b_2 &= \frac{1 - \cos\omega_0}{2} \\
    a_0 &= 1 + \alpha_{Q_{dB}} \\
    a_1 &= -2 \cos\omega_0 \\
    a_2 &= 1 - \alpha_{Q_{dB}}
  \end{align*}
$$
"highpass"
$$
  \begin{align*}
    b_0 &= \frac{1 + \cos\omega_0}{2} \\
    b_1 &= -(1 + \cos\omega_0) \\
    b_2 &= \frac{1 + \cos\omega_0}{2} \\
    a_0 &= 1 + \alpha_{Q_{dB}} \\
    a_1 &= -2 \cos\omega_0 \\
    a_2 &= 1 - \alpha_{Q_{dB}}
  \end{align*}
$$
"bandpass"
$$
  \begin{align*}
    b_0 &= \alpha_Q \\
    b_1 &= 0 \\
    b_2 &= -\alpha_Q \\
    a_0 &= 1 + \alpha_Q \\
    a_1 &= -2 \cos\omega_0 \\
    a_2 &= 1 - \alpha_Q
  \end{align*}
$$
"notch"
$$
  \begin{align*}
    b_0 &= 1 \\
    b_1 &= -2\cos\omega_0 \\
    b_2 &= 1 \\
    a_0 &= 1 + \alpha_Q \\
    a_1 &= -2 \cos\omega_0 \\
    a_2 &= 1 - \alpha_Q
  \end{align*}
$$
"allpass"
$$
  \begin{align*}
    b_0 &= 1 - \alpha_Q \\
    b_1 &= -2\cos\omega_0 \\
    b_2 &= 1 + \alpha_Q \\
    a_0 &= 1 + \alpha_Q \\
    a_1 &= -2 \cos\omega_0 \\
    a_2 &= 1 - \alpha_Q
  \end{align*}
$$
"peaking"
$$
  \begin{align*}
    b_0 &= 1 + \alpha_Q\, A \\
    b_1 &= -2\cos\omega_0 \\
    b_2 &= 1 - \alpha_Q\,A \\
    a_0 &= 1 + \frac{\alpha_Q}{A} \\
    a_1 &= -2 \cos\omega_0 \\
    a_2 &= 1 - \frac{\alpha_Q}{A}
  \end{align*}
$$
"lowshelf"
$$
  \begin{align*}
    b_0 &= A \left[ (A+1) - (A-1) \cos\omega_0 + 2 \alpha_S \sqrt{A})\right] \\
    b_1 &= 2 A \left[ (A-1) - (A+1) \cos\omega_0 )\right] \\
    b_2 &= A \left[ (A+1) - (A-1) \cos\omega_0 - 2 \alpha_S \sqrt{A}) \right] \\
    a_0 &= (A+1) + (A-1) \cos\omega_0 + 2 \alpha_S \sqrt{A} \\
    a_1 &= -2 \left[ (A-1) + (A+1) \cos\omega_0\right] \\
    a_2 &= (A+1) + (A-1) \cos\omega_0 - 2 \alpha_S \sqrt{A})
  \end{align*}
$$
"highshelf"
$$
  \begin{align*}
    b_0 &= A\left[ (A+1) + (A-1)\cos\omega_0 + 2\alpha_S\sqrt{A} )\right] \\
    b_1 &= -2A\left[ (A-1) + (A+1)\cos\omega_0 )\right] \\
    b_2 &= A\left[ (A+1) + (A-1)\cos\omega_0 - 2\alpha_S\sqrt{A} )\right] \\
    a_0 &= (A+1) - (A-1)\cos\omega_0 + 2\alpha_S\sqrt{A} \\
    a_1 &= 2\left[ (A-1) - (A+1)\cos\omega_0\right] \\
    a_2 &= (A+1) - (A-1)\cos\omega_0 - 2\alpha_S\sqrt{A}
  \end{align*}
$$

1.14. The ChannelMergerNode Interface

The ChannelMergerNode is for use in more advanced applications and would often be used in conjunction with ChannelSplitterNode.

Property Value Notes
numberOfInputs see notes Defaults to 6, but is determined by ChannelMergerOptions,numberOfInputs or the value specified by createChannelMerger.
numberOfOutputs 1
channelCount 1 Has channelCount constraints
channelCountMode "explicit" Has channelCountMode constraints
channelInterpretation "speakers"
tail-time No

This interface represents an AudioNode for combining channels from multiple audio streams into a single audio stream. It has a variable number of inputs (defaulting to 6), but not all of them need be connected. There is a single output whose audio stream has a number of channels equal to the number of inputs when any of the inputs is actively processing. If none of the inputs are actively processing, then output is a single channel of silence.

To merge multiple inputs into one stream, each input gets downmixed into one channel (mono) based on the specified mixing rule. An unconnected input still counts as one silent channel in the output. Changing input streams does not affect the order of output channels.

For example, if a default ChannelMergerNode has two connected stereo inputs, the first and second input will be downmixed to mono respectively before merging. The output will be a 6-channel stream whose first two channels are be filled with the first two (downmixed) inputs and the rest of channels will be silent.

Also the ChannelMergerNode can be used to arrange multiple audio streams in a certain order for the multi-channel speaker array such as 5.1 surround set up. The merger does not interpret the channel identities (such as left, right, etc.), but simply combines channels in the order that they are input.

channel merger
A diagram of ChannelMerger

ChannelMergerNode/ChannelMergerNode

Firefox53+SafariNoneChrome55+
Opera42+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android53+iOS SafariNoneChrome for Android55+Android WebView55+Samsung Internet6.0+Opera Mobile42+

ChannelMergerNode

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+
[Exposed=Window]
interface ChannelMergerNode : AudioNode {
  constructor (BaseAudioContext context, optional ChannelMergerOptions options = {});
};

1.14.1. Constructors

ChannelMergerNode(context, options)

When the constructor is called with a BaseAudioContext c and an option object option, the user agent MUST initialize the AudioNode this, with context and options as arguments.

Arguments for the ChannelMergerNode.constructor() method.
Parameter Type Nullable Optional Description
context BaseAudioContext The BaseAudioContext this new ChannelMergerNode will be associated with.
options ChannelMergerOptions Optional initial parameter value for this ChannelMergerNode.

1.14.2. ChannelMergerOptions

dictionary ChannelMergerOptions : AudioNodeOptions {
  unsigned long numberOfInputs = 6;
};
1.14.2.1. Dictionary ChannelMergerOptions Members
numberOfInputs, of type unsigned long, defaulting to 6

The number inputs for the ChannelMergerNode. See createChannelMerger() for constraints on this value.

1.15. The ChannelSplitterNode Interface

The ChannelSplitterNode is for use in more advanced applications and would often be used in conjunction with ChannelMergerNode.

Property Value Notes
numberOfInputs 1
numberOfOutputs see notes This defaults to 6, but is otherwise determined from ChannelSplitterOptions.numberOfOutputs or the value specified by createChannelSplitter or the numberOfOutputs member of the ChannelSplitterOptions dictionary for the constructor.
channelCount numberOfOutputs Has channelCount constraints
channelCountMode "explicit" Has channelCountMode constraints
channelInterpretation "discrete" Has channelInterpretation constraints
tail-time No

This interface represents an AudioNode for accessing the individual channels of an audio stream in the routing graph. It has a single input, and a number of "active" outputs which equals the number of channels in the input audio stream. For example, if a stereo input is connected to an ChannelSplitterNode then the number of active outputs will be two (one from the left channel and one from the right). There are always a total number of N outputs (determined by the numberOfOutputs parameter to the AudioContext method createChannelSplitter()), The default number is 6 if this value is not provided. Any outputs which are not "active" will output silence and would typically not be connected to anything.

channel splitter
A diagram of a ChannelSplitter

Please note that in this example, the splitter does not interpret the channel identities (such as left, right, etc.), but simply splits out channels in the order that they are input.

One application for ChannelSplitterNode is for doing "matrix mixing" where individual gain control of each channel is desired.

ChannelSplitterNode/ChannelSplitterNode

Firefox53+SafariNoneChrome55+
Opera42+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android53+iOS SafariNoneChrome for Android55+Android WebView55+Samsung Internet6.0+Opera Mobile42+

ChannelSplitterNode

In all current engines.

Firefox25+Safari6+Chrome14+
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android25+iOS SafariYesChrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+
[Exposed=Window]
interface ChannelSplitterNode : AudioNode {
  constructor (BaseAudioContext context, optional ChannelSplitterOptions options = {});
};

1.15.1. Constructors

ChannelSplitterNode(context, options)

When the constructor is called with a BaseAudioContext c and an option object option, the user agent MUST initialize the AudioNode this, with context and options as arguments.

Arguments for the ChannelSplitterNode.constructor() method.
Parameter Type Nullable Optional Description
context BaseAudioContext The BaseAudioContext this new ChannelSplitterNode will be associated with.
options ChannelSplitterOptions Optional initial parameter value for this ChannelSplitterNode.

1.15.2. ChannelSplitterOptions

dictionary ChannelSplitterOptions : AudioNodeOptions {
  unsigned long numberOfOutputs = 6;
};
1.15.2.1. Dictionary ChannelSplitterOptions Members
numberOfOutputs, of type unsigned long, defaulting to 6

The number outputs for the ChannelSplitterNode. See createChannelSplitter() for constraints on this value.

1.16. The ConstantSourceNode Interface

ConstantSourceNode

Firefox52+SafariNoneChrome56+
Opera43+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android52+iOS SafariNoneChrome for Android56+Android WebView56+Samsung Internet6.0+Opera Mobile43+

This interface represents a constant audio source whose output is nominally a constant value. It is useful as a constant source node in general and can be used as if it were a constructible AudioParam by automating its offset or connecting another node to it.

The single output of this node consists of one channel (mono).

Property Value Notes
numberOfInputs 0
numberOfOutputs 1
channelCount 2
channelCountMode "max"