RTCRtpStreamStats: pliCount property - Web APIs

RTCRtpStreamStats: pliCount property
====================================

 The **`pliCount`** property of the
 `RTCRtpStreamStats` dictionary states the number of times the stream's
 receiving end sent a **Picture Loss Indication** (**PLI**)
 packet to the sender.

 A PLI packet indicates that some amount of encoded video
 data has been lost for one or more frames.

Value
-----

 An integer value indicating the number of times a PLI packet was sent by the stream's
 receiver to the sender.

 A PLI message is used by video decoders (running on the receiving end of the stream) to
 notify the encoder (the sender) that an undefined amount of coded video data, which may
 span frame boundaries, has been lost.

 This may trigger the sender to send a full frame in order to allow the receiver to
 re-synchronize, since lost data may be an irrecoverable situation for decoding media.
 However, the primary purpose of this message is to allow the sender to consider
 techniques to mitigate network performance issues. This is often achieved by methods
 such as increasing the compression, lowering resolution, or finding other ways to reduce
 the bit rate of the stream.

**Note:** This value is only available on the receiver, and only for
 video media.

Specifications
--------------

#### No specification found

No specification data found for `api.RTCRtpStreamStats.pliCount`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* RFC 4585, section 6.3.1: Definition of "PLI messages" in the document *Extended
RTP Profile for Real-time Transport Control Protocol (RTCP)-Based Feedback
(RTP/AVPF)*.


RTCRtpStreamStats: transportId property - Web APIs

RTCRtpStreamStats: transportId property
=======================================

 The `RTCRtpStreamStats` dictionary's
 **`transportId`** property is a string which uniquely
 identifies the object from which the statistics contained in the
 `RTCTransportStats` properties in the
 `RTCStatsReport`.

Value
-----

 A string uniquely identifying the source of the statistics contained
 the `RTCTransportStats` properties in the `RTCStatsReport`.

Specifications
--------------

#### No specification found

No specification data found for `api.RTCRtpStreamStats.transportId`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


RTCRtpStreamStats: firCount property - Web APIs

RTCRtpStreamStats: firCount property
====================================

 The **`firCount`** property of the
 `RTCRtpStreamStats` dictionary indicates the number of **Full Intra
Request** (**FIR**) packets have been sent by the receiver to
 the sender.

 This is a measure of how often the stream falls behind and has to
 skip frames in order to catch up.

Value
-----

 An integer value indicating how many FIR packets have been received by the sender
 during the current connection. This value is available only on receivers for video
 tracks.

 The receiver sends a FIR packet to the sender any time it falls behind or loses packets
 and cannot decode the incoming stream any longer because of the lost data. This tells
 the sender to send a full frame instead of a delta frame, so that the receiver can catch
 up.

 The higher `firCount` is, the more often frames were dropped, which may be
 an indication that the media's bit rate is too high for the available bandwidth, or that
 the receiving device is overburdened and is therefore unable to process the incoming
 data.

Specifications
--------------

#### No specification found

No specification data found for `api.RTCRtpStreamStats.firCount`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


XPathEvaluator: evaluate() method - Web APIs

XPathEvaluator: evaluate() method
=================================

 The `evaluate()` method of the `XPathEvaluator` interface
 executes an XPath expression on the given node or document and returns an
 `XPathResult`.

Syntax
------

```js
evaluate(expression, contextNode)
evaluate(expression, contextNode, resolver)
evaluate(expression, contextNode, resolver, type)
evaluate(expression, contextNode, resolver, type, result)
```

### Parameters

`expression`

 A string representing the XPath expression to be parsed and
 evaluated.

`contextNode`

A `Node` representing the context to use for evaluating the expression.

`resolver` Optional

 Permits translation of all prefixes, including the `xml` namespace
 prefix, within the XPath expression into appropriate namespace URIs.

`type` Optional

 Specifies the type of result to be returned by evaluating the expression. This must
 be one of the `XPathResult.Constants`.

`result` Optional

 Allows to specify a result object which may be reused and returned by this method.
 If this is specified as `null` or the implementation does not reuse the
 specified result, a new result object will be returned.

### Return value

 An `XPathResult` object representing the result of evaluating the XPath
 expression.

### Exceptions

#### INVALID\_EXPRESSION\_ERR

 If the expression is not legal according to the rules of the
 `XPathEvaluator`, an `XPathException` of type
 `INVALID_EXPRESSION_ERR` is raised.

#### TYPE\_ERR

 In case result cannot be converted to the specified type, an
 `XPathException` of type `TYPE_ERR` is raised.

#### NAMESPACE\_ERR

 If the expression contains namespace prefixes which cannot be resolved by the specified
 `XPathNSResolver`, a `DOMException` of type
 `NAMESPACE_ERROR` is raised.

#### WRONG\_DOCUMENT\_ERR

 If the provided context node is from a document that is not supported by the
 `XPathEvaluator`, a `DOMException` of type
 `WRONG_DOCUMENT_ERR` is raised.

#### NOT\_SUPPORTED\_ERR

 If the provided context node is not a type permitted as an XPath context node or the
 request type is not permitted by the `XPathEvaluator`, a
 `DOMException` of type `NOT_SUPPORTED_ERR` is raised.

Examples
--------

The following example shows the use of the `evaluate()` method.

### HTML

```html
<div>XPath example</div>
<div>Number of <div>s: <output></output></div>
```

### JavaScript

```js
const evaluator = new XPathEvaluator();
const result = evaluator.evaluate(
  "//div",
  document,
  null,
  XPathResult.ORDERED\_NODE\_SNAPSHOT\_TYPE,
);
document.querySelector("output").textContent = result.snapshotLength;
```

### Result

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-xpathevaluatorbase-evaluate |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


XPathEvaluator: createExpression() method - Web APIs

XPathEvaluator: createExpression() method
=========================================

 This method compiles an `XPathExpression` which can then be used for
 (repeated) evaluations of the XPath expression.

Syntax
------

```js
createExpression(expression)
createExpression(expression, resolver)
```

### Parameters

`expression`

A string representing the XPath expression to be created.

`resolver` Optional

 Permits translation of all prefixes, including the `xml` namespace
 prefix, within the XPath expression into appropriate namespace URIs.

### Return value

 A `XPathExpression` representing the compiled form of the XPath
 expression.

### Exceptions

#### INVALID\_EXPRESSION\_ERR

 If the expression is not legal according to the rules of the
 `XPathEvaluator`, an `XPathException` of type
 `INVALID_EXPRESSION_ERR` is raised.

#### NAMESPACE\_ERR

 If the expression contains namespace prefixes which cannot be resolved by the specified
 `XPathNSResolver`, a `DOMException` of type
 `NAMESPACE_ERROR` is raised.

Examples
--------

The following example shows the use of the `evaluate()` method.

### HTML

```html
<div>XPath example</div>
<div>Number of <div>s: <output></output></div>
```

### JavaScript

```js
const xpath = "//div";
const evaluator = new XPathEvaluator();
const expression = evaluator.createExpression(xpath);
const result = expression.evaluate(
  document,
  XPathResult.ORDERED\_NODE\_SNAPSHOT\_TYPE,
);
document.querySelector("output").textContent = result.snapshotLength;
```

### Result

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-xpathevaluatorbase-createexpression |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Document.createExpression()`
* `XPathExpression`


XPathEvaluator: XPathEvaluator() constructor - Web APIs

XPathEvaluator: XPathEvaluator() constructor
============================================

The **`XPathEvaluator()`** constructor creates a new `XPathEvaluator`.

Syntax
------

```js
new XPathEvaluator()
```

### Parameters

None.

### Return value

A new `XPathEvaluator` object.

Examples
--------

### Count the number of `<div>` elements

The following example shows the use of the `XPathEvaluator` interface.

#### HTML

```html
<div>XPath example</div>
<div>Number of <div> elements: <output></output></div>
```

#### JavaScript

```js
const xpath = "//div";
const evaluator = new XPathEvaluator();
const expression = evaluator.createExpression(xpath);
const result = expression.evaluate(
  document,
  XPathResult.ORDERED\_NODE\_SNAPSHOT\_TYPE,
);
document.querySelector("output").textContent = result.snapshotLength;
```

#### Result

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-xpathevaluator-xpathevaluator |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


XPathEvaluator: createNSResolver() method - Web APIs

XPathEvaluator: createNSResolver() method
=========================================

 This method adapts any DOM node to resolve namespaces so that an XPath expression can
 be easily evaluated relative to the context of the node where it appeared within the
 document.

 This adapter works like the DOM Level 3 method `Node.lookupNamespaceURI()` in resolving the namespace URI from a given prefix using
 the current information available in the node's hierarchy at the time the method is
 called, also correctly resolving the implicit `xml` prefix.

Syntax
------

```js
createNSResolver(nodeResolver)
```

### Parameters

`nodeResolver`

A `Node` to be used as a context for namespace resolution.

### Return value

 An `XPathNSResolver` object which resolves namespaces with respect to the
 definitions in scope for a specified node.

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-xpathevaluatorbase-creatensresolver |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Document.createNSResolver()`
* `XPathExpression`


BaseAudioContext: createPanner() method - Web APIs

BaseAudioContext: createPanner() method
=======================================

 The `createPanner()` method of the `BaseAudioContext`
 Interface is used to create a new `PannerNode`, which is used to
 spatialize an incoming audio stream in 3D space.

 The panner node is spatialized in relation to the AudioContext's
 `AudioListener` (defined by the `AudioContext.listener`
 attribute), which represents the position and orientation of the person listening to the
 audio.

**Note:** The `PannerNode()`
 constructor is the recommended way to create a `PannerNode`; see
 Creating an AudioNode.

Syntax
------

```js
createPanner()
```

### Parameters

None.

### Return value

A `PannerNode`.

Examples
--------

 In the following example, you can see an example of how the `createPanner()`
 method, `AudioListener` and `PannerNode` would be used to
 control audio spatialization. Generally you will define the position in 3D space that
 your audio listener and panner (source) occupy initially, and then update the position
 of one or both of these as the application is used. You might be moving a character
 around inside a game world for example, and wanting delivery of audio to change
 realistically as your character moves closer to or further away from a music player such
 as a stereo. In the example you can see this being controlled by the functions
 `moveRight()`, `moveLeft()`, etc., which set new values for the
 panner position via the `PositionPanner()` function.

 To see a complete implementation, check out our panner-node example
 (view the source code) — this demo transports you to the 2.5D "Room of metal", where you can
 play a track on a boom box and then walk around the boom box to see how the sound
 changes!

 Note how we have used some feature detection to either give the browser the newer
 property values (like `AudioListener.forwardX`) for setting position, etc.
 if it supports those, or older methods (like
 `AudioListener.setOrientation()`) if it still supports those but not the
 new properties.

```js
// set up listener and panner position information
const WIDTH = window.innerWidth;
const HEIGHT = window.innerHeight;

const xPos = Math.floor(WIDTH / 2);
const yPos = Math.floor(HEIGHT / 2);
const zPos = 295;

// define other variables

const audioCtx = new AudioContext();

const panner = audioCtx.createPanner();
panner.panningModel = "HRTF";
panner.distanceModel = "inverse";
panner.refDistance = 1;
panner.maxDistance = 10000;
panner.rolloffFactor = 1;
panner.coneInnerAngle = 360;
panner.coneOuterAngle = 0;
panner.coneOuterGain = 0;

if (panner.orientationX) {
  panner.orientationX.setValueAtTime(1, audioCtx.currentTime);
  panner.orientationY.setValueAtTime(0, audioCtx.currentTime);
  panner.orientationZ.setValueAtTime(0, audioCtx.currentTime);
} else {
  panner.setOrientation(1, 0, 0);
}

const listener = audioCtx.listener;

if (listener.forwardX) {
  listener.forwardX.setValueAtTime(0, audioCtx.currentTime);
  listener.forwardY.setValueAtTime(0, audioCtx.currentTime);
  listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime);
  listener.upX.setValueAtTime(0, audioCtx.currentTime);
  listener.upY.setValueAtTime(1, audioCtx.currentTime);
  listener.upZ.setValueAtTime(0, audioCtx.currentTime);
} else {
  listener.setOrientation(0, 0, -1, 0, 1, 0);
}

let source;

const play = document.querySelector(".play");
const stop = document.querySelector(".stop");

const boomBox = document.querySelector(".boom-box");

const listenerData = document.querySelector(".listener-data");
const pannerData = document.querySelector(".panner-data");

leftBound = -xPos + 50;
rightBound = xPos - 50;

xIterator = WIDTH / 150;

// listener will always be in the same place for this demo

if (listener.positionX) {
  listener.positionX.setValueAtTime(xPos, audioCtx.currentTime);
  listener.positionY.setValueAtTime(yPos, audioCtx.currentTime);
  listener.positionZ.setValueAtTime(300, audioCtx.currentTime);
} else {
  listener.setPosition(xPos, yPos, 300);
}

listenerData.textContent = `Listener data: X ${xPos} Y ${yPos} Z 300`;

// panner will move as the boombox graphic moves around on the screen
function positionPanner() {
  if (panner.positionX) {
    panner.positionX.setValueAtTime(xPos, audioCtx.currentTime);
    panner.positionY.setValueAtTime(yPos, audioCtx.currentTime);
    panner.positionZ.setValueAtTime(zPos, audioCtx.currentTime);
  } else {
    panner.setPosition(xPos, yPos, zPos);
  }
  pannerData.textContent = `Panner data: X ${xPos} Y ${yPos} Z ${zPos}`;
}
```

**Note:** In terms of working out what position values to apply to the
 listener and panner, to make the sound appropriate to what the visuals are doing on
 screen, there is quite a bit of math involved, but you will soon get used to it with a
 bit of experimentation.

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-createpanner |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: createPeriodicWave() method - Web APIs

BaseAudioContext: createPeriodicWave() method
=============================================

 The `createPeriodicWave()` method of the `BaseAudioContext` Interface
 is used to create a `PeriodicWave`, which is used to define a periodic waveform
 that can be used to shape the output of an `OscillatorNode`.

Syntax
------

```js
createPeriodicWave(real, imag)
createPeriodicWave(real, imag, constraints)
```

### Parameters

`real`

An array of cosine terms (traditionally the A terms).

`imag`

An array of sine terms (traditionally the B terms).

 The `real` and `imag` arrays have to have the same length,
 otherwise an error is thrown.

`constraints` Optional

 An dictionary object that specifies whether normalization should be disabled (if
 not specified, normalization is enabled by default.) It takes one property:

`disableNormalization`

 If set to `true`,
 normalization is disabled for the periodic wave. The default is
 `false`.

**Note:** If normalized, the resulting wave will have a maximum absolute peak value of 1.

### Return value

A `PeriodicWave`.

Examples
--------

 The following example illustrates simple usage of `createPeriodicWave()`, to
 create a `PeriodicWave` object containing a simple sine wave.

```js
const real = new Float32Array(2);
const imag = new Float32Array(2);
const ac = new AudioContext();
const osc = ac.createOscillator();

real[0] = 0;
imag[0] = 0;
real[1] = 1;
imag[1] = 0;

const wave = ac.createPeriodicWave(real, imag, { disableNormalization: true });

osc.setPeriodicWave(wave);

osc.connect(ac.destination);

osc.start();
osc.stop(2);
```

 This works because a sound that contains only a fundamental tone is by definition a
 sine wave

 Here, we create a `PeriodicWave` with two values. The first value is the DC
 offset, which is the value at which the oscillator starts. 0 is good here, because we
 want to start the curve at the middle of the [-1.0; 1.0] range.

 The second and subsequent values are sine and cosine components. You can think of it as
 the result of a Fourier transform, where you get frequency domain values from time
 domain value. Here, with `createPeriodicWave()`, you specify the
 frequencies, and the browser performs an inverse Fourier transform to get a time
 domain buffer for the frequency of the oscillator. Here, we only set one component at
 full volume (1.0) on the fundamental tone, so we get a sine wave. Bear in mind the
 fundamental tone is the oscillator's frequency (which, by default, is 440 Hz).
 Thus, by altering the oscillator's frequency we are in effect shifting the frequency
 of this periodic wave along with it.

 The coefficients of the Fourier transform should be given in *ascending* order
 (i.e.

(

a
+
b
i

)

e
i

,

(

c
+
d
i

)

e

2
i

,

(

f
+
g
i

)

e

3
i

 \left(a+bi\right)e^{i} , \left(c+di\right)e^{2i} ,
 \left(f+gi\right)e^{3i}

etc.) and can be positive or negative. A simple way of manually obtaining such
 coefficients (though not the best) is to use a graphing calculator.

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-createperiodicwave |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: currentTime property - Web APIs

BaseAudioContext: currentTime property
======================================

 The `currentTime` read-only property of the `BaseAudioContext`
 interface returns a double representing an ever-increasing hardware timestamp in seconds that
 can be used for scheduling audio playback, visualizing timelines, etc. It starts at 0.

Value
-----

A floating point number.

Examples
--------

```js
const audioCtx = new AudioContext();
// Older webkit/blink browsers require a prefix

// …

console.log(audioCtx.currentTime);
```

Reduced time precision
----------------------

 To offer protection against timing attacks and fingerprinting, the precision of
 `audioCtx.currentTime` might get rounded depending on browser settings.
 In Firefox, the `privacy.reduceTimerPrecision` preference is enabled by
 default and defaults to 20us in Firefox 59; in 60 it will be 2ms.

```js
// reduced time precision (2ms) in Firefox 60
audioCtx.currentTime;
// 23.404
// 24.192
// 25.514
// …

// reduced time precision with `privacy.resistFingerprinting` enabled
audioCtx.currentTime;
// 49.8
// 50.6
// 51.7
// …
```

 In Firefox, you can also enabled `privacy.resistFingerprinting`, the
 precision will be 100ms or the value of
 `privacy.resistFingerprinting.reduceTimerPrecision.microseconds`, whichever
 is larger.

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-currenttime |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using Web Audio API


BaseAudioContext: createDynamicsCompressor() method - Web APIs

BaseAudioContext: createDynamicsCompressor() method
===================================================

 The `createDynamicsCompressor()` method of the `BaseAudioContext` Interface is used to create a
 `DynamicsCompressorNode`, which can be used to apply compression to an
 audio signal.

 Compression lowers the volume of the loudest parts of the signal and raises the volume
 of the softest parts. Overall, a louder, richer, and fuller sound can be achieved. It is
 especially important in games and musical applications where large numbers of individual
 sounds are played simultaneously, where you want to control the overall signal level and
 help avoid clipping (distorting) of the audio output.

**Note:** The `DynamicsCompressorNode()`
 constructor is the recommended way to create a `DynamicsCompressorNode`; see
 Creating an AudioNode.

Syntax
------

```js
createDynamicsCompressor()
```

### Parameters

None.

### Return value

A `DynamicsCompressorNode`.

Examples
--------

 The code below demonstrates a simple usage of `createDynamicsCompressor()`
 to add compression to an audio track. For a more complete example, have a look at our basic Compressor example (view the source code).

```js
// Create a MediaElementAudioSourceNode
// Feed the HTMLMediaElement into it
const source = audioCtx.createMediaElementSource(myAudio);

// Create a compressor node
const compressor = audioCtx.createDynamicsCompressor();
compressor.threshold.setValueAtTime(-50, audioCtx.currentTime);
compressor.knee.setValueAtTime(40, audioCtx.currentTime);
compressor.ratio.setValueAtTime(12, audioCtx.currentTime);
compressor.attack.setValueAtTime(0, audioCtx.currentTime);
compressor.release.setValueAtTime(0.25, audioCtx.currentTime);

// connect the AudioBufferSourceNode to the destination
source.connect(audioCtx.destination);

button.onclick = () => {
  const active = button.getAttribute("data-active");
  if (active === "false") {
    button.setAttribute("data-active", "true");
    button.textContent = "Remove compression";

    source.disconnect(audioCtx.destination);
    source.connect(compressor);
    compressor.connect(audioCtx.destination);
  } else if (active === "true") {
    button.setAttribute("data-active", "false");
    button.textContent = "Add compression";

    source.disconnect(compressor);
    compressor.disconnect(audioCtx.destination);
    source.connect(audioCtx.destination);
  }
};
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-createdynamicscompressor |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: state property - Web APIs

BaseAudioContext: state property
================================

 The `state` read-only property of the `BaseAudioContext`
 interface returns the current state of the `AudioContext`.

Value
-----

A string. Possible values are:

`suspended`

 The audio context has been suspended (with the
 `AudioContext.suspend()` method.)

`running`

The audio context is running normally.

`closed`

 The audio context has been closed (with the
 `AudioContext.close()` method.)

Examples
--------

### Handling state changes

 The following snippet is taken from our AudioContext states demo (see it running live.) The `onstatechange` handler is used to log the
 current state to the console every time it changes.

```js
audioCtx.onstatechange = () => {
  console.log(audioCtx.state);
};
```

### Resuming interrupted play states in iOS Safari

 In iOS Safari, when a user leaves the page (e.g. switches tabs, minimizes the browser, or
 turns off the screen)
 the audio context's state changes to "interrupted" and needs to be resumed. For example:

```js
function play() {
  if (audioCtx.state === "interrupted") {
    audioCtx.resume().then(() => play());
    return;
  }
  // rest of the play() function
}
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-state |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: createConstantSource() method - Web APIs

BaseAudioContext: createConstantSource() method
===============================================

 The **`createConstantSource()`**
 property of the `BaseAudioContext` interface creates a
 `ConstantSourceNode` object, which is an audio source that continuously
 outputs a monaural (one-channel) sound signal whose samples all have the same
 value.

**Note:** The `ConstantSourceNode()`
 constructor is the recommended way to create a `ConstantSourceNode`; see
 Creating an AudioNode.

Syntax
------

```js
createConstantSource()
```

### Parameters

None.

### Return value

A `ConstantSourceNode` instance.

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-createconstantsource |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


BaseAudioContext: createWaveShaper() method - Web APIs

BaseAudioContext: createWaveShaper() method
===========================================

 The `createWaveShaper()` method of the `BaseAudioContext`
 interface creates a `WaveShaperNode`, which represents a non-linear
 distortion. It is used to apply distortion effects to your audio.

**Note:** The `WaveShaperNode()`
 constructor is the recommended way to create a `WaveShaperNode`; see
 Creating an AudioNode.

Syntax
------

```js
createWaveShaper()
```

### Parameters

None.

### Return value

A `WaveShaperNode`.

Examples
--------

 The following example shows basic usage of an AudioContext to create a wave shaper node.
 For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 108–193 for relevant code).

**Note:** Sigmoid functions are commonly used for distortion curves
 because of their natural properties. Their S-shape, for instance, helps create a
 smoother sounding result. We found the below distortion curve code on Stack Overflow.

```js
const audioCtx = new AudioContext();
const distortion = audioCtx.createWaveShaper();

// …

function makeDistortionCurve(amount) {
  const k = typeof amount === "number" ? amount : 50;
  const n_samples = 44100;
  const curve = new Float32Array(n_samples);
  const deg = Math.PI / 180;

  for (let i = 0; i < n_samples; i++) {
    const x = (i \* 2) / n_samples - 1;
    curve[i] = ((3 + k) \* x \* 20 \* deg) / (Math.PI + k \* Math.abs(x));
  }
  return curve;
}

// …

distortion.curve = makeDistortionCurve(400);
distortion.oversample = "4x";
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-createwaveshaper |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: createIIRFilter() method - Web APIs

BaseAudioContext: createIIRFilter() method
==========================================

 The **`createIIRFilter()`** method of the `BaseAudioContext` interface creates an `IIRFilterNode`,
 which represents a general **infinite impulse response** (IIR) filter which can be configured to serve as various types
 of filter.

**Note:** The `IIRFilterNode()`
 constructor is the recommended way to create a `IIRFilterNode`; see
 Creating an AudioNode.

Syntax
------

```js
createIIRFilter(feedforward, feedback)
```

### Parameters

`feedforward`

 An array of floating-point values specifying the feedforward (numerator)
 coefficients for the transfer function of the IIR filter. The maximum length of this
 array is 20, and at least one value must be nonzero.

`feedback`

 An array of floating-point values specifying the feedback (denominator) coefficients
 for the transfer function of the IIR filter. This array may have up to 20 members, the
 first of which must not be zero.

### Return value

 An `IIRFilterNode` implementing the filter with the specified feedback and
 feedforward coefficient arrays.

### Exceptions

`InvalidStateError` `DOMException`

 Thrown if all of the `feedforward` coefficients are 0, or if the first
 `feedback` coefficient is 0.

`NotSupportedError` `DOMException`

Thrown if one or both of the input arrays exceeds 20 members.

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-createiirfilter |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API
* `IIRFilterNode`
* `AudioNode`


BaseAudioContext: createBiquadFilter() method - Web APIs

BaseAudioContext: createBiquadFilter() method
=============================================

 The `createBiquadFilter()` method of the `BaseAudioContext`
 interface creates a `BiquadFilterNode`, which represents a second order
 filter configurable as several different common filter types.

**Note:** The `BiquadFilterNode()` constructor is the
 recommended way to create a `BiquadFilterNode`; see
 Creating an AudioNode.

Syntax
------

```js
createBiquadFilter()
```

### Parameters

None.

### Return value

A `BiquadFilterNode`.

Examples
--------

 The following example shows basic usage of an AudioContext to create a Biquad filter node.
 For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 108–193 for relevant code).

```js
const audioCtx = new AudioContext();

//set up the different audio nodes we will use for the app
const analyser = audioCtx.createAnalyser();
const distortion = audioCtx.createWaveShaper();
const gainNode = audioCtx.createGain();
const biquadFilter = audioCtx.createBiquadFilter();
const convolver = audioCtx.createConvolver();

// connect the nodes together

source = audioCtx.createMediaStreamSource(stream);
source.connect(analyser);
analyser.connect(distortion);
distortion.connect(biquadFilter);
biquadFilter.connect(convolver);
convolver.connect(gainNode);
gainNode.connect(audioCtx.destination);

// Manipulate the Biquad filter

biquadFilter.type = "lowshelf";
biquadFilter.frequency.setValueAtTime(1000, audioCtx.currentTime);
biquadFilter.gain.setValueAtTime(25, audioCtx.currentTime);
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-createbiquadfilter |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: createChannelSplitter() method - Web APIs

BaseAudioContext: createChannelSplitter() method
================================================

 The `createChannelSplitter()` method of the `BaseAudioContext` Interface is used to create a `ChannelSplitterNode`,
 which is used to access the individual channels of an audio stream and process them separately.

**Note:** The `ChannelSplitterNode()`
 constructor is the recommended way to create a `ChannelSplitterNode`; see
 Creating an AudioNode.

Syntax
------

```js
createChannelSplitter(numberOfOutputs)
```

### Parameters

`numberOfOutputs`

 The number of channels in the input audio stream that you want to output separately;
 the default is 6 if this parameter is not specified.

### Return value

A `ChannelSplitterNode`.

Examples
--------

 The following simple example shows how you could separate a stereo track (say, a piece
 of music), and process the left and right channel differently. To use them, you need to
 use the second and third parameters of the `AudioNode.connect(AudioNode)`
 method, which allow you to specify the index of the channel to connect from and the
 index of the channel to connect to.

```js
const ac = new AudioContext();
ac.decodeAudioData(someStereoBuffer, (data) => {
  const source = ac.createBufferSource();
  source.buffer = data;
  const splitter = ac.createChannelSplitter(2);
  source.connect(splitter);
  const merger = ac.createChannelMerger(2);

  // Reduce the volume of the left channel only
  const gainNode = ac.createGain();
  gainNode.gain.setValueAtTime(0.5, ac.currentTime);
  splitter.connect(gainNode, 0);

  // Connect the splitter back to the second input of the merger: we
  // effectively swap the channels, here, reversing the stereo image.
  gainNode.connect(merger, 0, 1);
  splitter.connect(merger, 1, 0);

  const dest = ac.createMediaStreamDestination();

  // Because we have used a ChannelMergerNode, we now have a stereo
  // MediaStream we can use to pipe the Web Audio graph to WebRTC,
  // MediaRecorder, etc.
  merger.connect(dest);
});
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-createchannelsplitter |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: createOscillator() method - Web APIs

BaseAudioContext: createOscillator() method
===========================================

 The `createOscillator()` method of the `BaseAudioContext`
 interface creates an `OscillatorNode`, a source representing a periodic
 waveform. It basically generates a constant tone.

**Note:** The `OscillatorNode()`
 constructor is the recommended way to create a `OscillatorNode`; see
 Creating an AudioNode.

Syntax
------

```js
createOscillator()
```

### Parameters

None.

### Return value

An `OscillatorNode`.

Examples
--------

 The following example shows basic usage of an AudioContext to create an oscillator
 node. For applied examples/information, check out our Violent Theremin demo (see app.js for relevant code); also see our `OscillatorNode` page for
 more information.

```js
// create web audio api context
const audioCtx = new AudioContext();

// create Oscillator node
const oscillator = audioCtx.createOscillator();

oscillator.type = "square";
oscillator.frequency.setValueAtTime(3000, audioCtx.currentTime); // value in hertz
oscillator.connect(audioCtx.destination);
oscillator.start();
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-createoscillator |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: createChannelMerger() method - Web APIs

BaseAudioContext: createChannelMerger() method
==============================================

 The `createChannelMerger()` method of the `BaseAudioContext` interface creates a `ChannelMergerNode`,
 which combines channels from multiple audio streams into a single audio stream.

**Note:** The `ChannelMergerNode()` constructor is the
 recommended way to create a `ChannelMergerNode`; see
 Creating an AudioNode.

Syntax
------

```js
createChannelMerger(numberOfInputs)
```

### Parameters

`numberOfInputs`

 The number of channels in the input audio streams, which the output stream will
 contain; the default is 6 if this parameter is not specified.

### Return value

A `ChannelMergerNode`.

Examples
--------

 The following example shows how you could separate a stereo track (say, a piece of
 music), and process the left and right channel differently. To use them, you need to use
 the second and third parameters of the `AudioNode.connect(AudioNode)`
 method, which allow you to specify both the index of the channel to connect from and the
 index of the channel to connect to.

```js
const ac = new AudioContext();
ac.decodeAudioData(someStereoBuffer, (data) => {
  const source = ac.createBufferSource();
  source.buffer = data;
  const splitter = ac.createChannelSplitter(2);
  source.connect(splitter);
  const merger = ac.createChannelMerger(2);

  // Reduce the volume of the left channel only
  const gainNode = ac.createGain();
  gainNode.gain.setValueAtTime(0.5, ac.currentTime);
  splitter.connect(gainNode, 0);

  // Connect the splitter back to the second input of the merger: we
  // effectively swap the channels, here, reversing the stereo image.
  gainNode.connect(merger, 0, 1);
  splitter.connect(merger, 1, 0);

  const dest = ac.createMediaStreamDestination();

  // Because we have used a ChannelMergerNode, we now have a stereo
  // MediaStream we can use to pipe the Web Audio graph to WebRTC,
  // MediaRecorder, etc.
  merger.connect(dest);
});
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-createchannelmerger |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: createBufferSource() method - Web APIs

BaseAudioContext: createBufferSource() method
=============================================

 The `createBufferSource()` method of the `BaseAudioContext`
 Interface is used to create a new `AudioBufferSourceNode`, which can be
 used to play audio data contained within an `AudioBuffer` object. `AudioBuffer`s are created using
 `BaseAudioContext.createBuffer` or returned by
 `BaseAudioContext.decodeAudioData` when it successfully decodes an audio
 track.

**Note:** The `AudioBufferSourceNode()`
 constructor is the recommended way to create a `AudioBufferSourceNode`; see
 Creating an AudioNode.

Syntax
------

```js
createBufferSource()
```

### Parameters

None.

### Return value

An `AudioBufferSourceNode`.

Examples
--------

 In this example, we create a two second buffer, fill it with white noise, and then play
 it via an `AudioBufferSourceNode`. The comments should clearly explain
 what is going on.

**Note:** You can also run the code live,
 or view the source.

```js
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const button = document.querySelector("button");
const pre = document.querySelector("pre");
const myScript = document.querySelector("script");

pre.innerHTML = myScript.innerHTML;

// Stereo
const channels = 2;
// Create an empty two second stereo buffer at the
// sample rate of the AudioContext
const frameCount = audioCtx.sampleRate \* 2.0;

const myArrayBuffer = audioCtx.createBuffer(
  channels,
  frameCount,
  audioCtx.sampleRate,
);

button.onclick = () => {
  // Fill the buffer with white noise;
  //just random values between -1.0 and 1.0
  for (let channel = 0; channel < channels; channel++) {
    // This gives us the actual ArrayBuffer that contains the data
    const nowBuffering = myArrayBuffer.getChannelData(channel);
    for (let i = 0; i < frameCount; i++) {
      // Math.random() is in [0; 1.0]
      // audio needs to be in [-1.0; 1.0]
      nowBuffering[i] = Math.random() \* 2 - 1;
    }
  }

  // Get an AudioBufferSourceNode.
  // This is the AudioNode to use when we want to play an AudioBuffer
  const source = audioCtx.createBufferSource();
  // set the buffer in the AudioBufferSourceNode
  source.buffer = myArrayBuffer;
  // connect the AudioBufferSourceNode to the
  // destination so we can hear the sound
  source.connect(audioCtx.destination);
  // start the source playing
  source.start();
};
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-createbuffersource |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: createAnalyser() method - Web APIs

BaseAudioContext: createAnalyser() method
=========================================

 The `createAnalyser()` method of the
 `BaseAudioContext` interface creates an `AnalyserNode`, which
 can be used to expose audio time and frequency data and create data visualizations.

**Note:** The `AnalyserNode()` constructor is the
 recommended way to create an `AnalyserNode`; see
 Creating an AudioNode.

**Note:** For more on using this node, see the
 `AnalyserNode` page.

Syntax
------

```js
createAnalyser()
```

### Parameters

None.

### Return value

An `AnalyserNode`.

Examples
--------

 The following example shows basic usage of an AudioContext to create an Analyser node,
 then use requestAnimationFrame() to collect time domain data repeatedly and draw an
 "oscilloscope style" output of the current audio input. For more complete applied
 examples/information, check out our Voice-change-O-matic demo (see
 app.js lines 108-193 for relevant code).

```js
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const analyser = audioCtx.createAnalyser();

// …

analyser.fftSize = 2048;
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
analyser.getByteTimeDomainData(dataArray);

// draw an oscilloscope of the current audio source

function draw() {
  drawVisual = requestAnimationFrame(draw);

  analyser.getByteTimeDomainData(dataArray);

  canvasCtx.fillStyle = "rgb(200 200 200)";
  canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);

  canvasCtx.lineWidth = 2;
  canvasCtx.strokeStyle = "rgb(0 0 0)";

  canvasCtx.beginPath();

  const sliceWidth = (WIDTH \* 1.0) / bufferLength;
  let x = 0;

  for (let i = 0; i < bufferLength; i++) {
    const v = dataArray[i] / 128.0;
    const y = (v \* HEIGHT) / 2;

    if (i === 0) {
      canvasCtx.moveTo(x, y);
    } else {
      canvasCtx.lineTo(x, y);
    }

    x += sliceWidth;
  }

  canvasCtx.lineTo(canvas.width, canvas.height / 2);
  canvasCtx.stroke();
}

draw();
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-createanalyser |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: createBuffer() method - Web APIs

BaseAudioContext: createBuffer() method
=======================================

 The `createBuffer()` method of the `BaseAudioContext`
 Interface is used to create a new, empty `AudioBuffer` object, which
 can then be populated by data, and played via an `AudioBufferSourceNode`

 For more details about audio buffers, check out the `AudioBuffer`
 reference page.

**Note:** `createBuffer()` used to be able to take compressed
 data and give back decoded samples, but this ability was removed from the specification,
 because all the decoding was done on the main thread, so
 `createBuffer()` was blocking other code execution. The asynchronous method
 `decodeAudioData()` does the same thing — takes compressed audio, such as an
 MP3 file, and directly gives you back an `AudioBuffer` that you can
 then play via an `AudioBufferSourceNode`. For simple use cases
 like playing an MP3, `decodeAudioData()` is what you should be using.

Syntax
------

```js
createBuffer(numOfChannels, length, sampleRate)
```

### Parameters

**Note:** For an in-depth explanation of how audio buffers work, and
 what these parameters mean, read Audio buffers: frames, samples and channels from our Basic concepts guide.

`numOfChannels`

 An integer representing the number of channels this buffer should have. The default
 value is 1, and all user agents must support at least 32 channels.

`length`

 An integer representing the size of the buffer in sample-frames (where each
 sample-frame is the size of a sample in bytes multiplied by
 `numOfChannels`). To determine the `length` to use for a
 specific number of seconds of audio, use `numSeconds * sampleRate`.

`sampleRate`

 The sample rate of the linear audio data in sample-frames per second. All browsers
 must support sample rates in at least the range 8,000 Hz to 96,000 Hz.

### Return value

An `AudioBuffer` configured based on the specified options.

### Exceptions

`NotSupportedError` `DOMException`

 Thrown if one or more of the options are negative or otherwise has an invalid value (such as
 `numberOfChannels` being higher than supported, or a
 `sampleRate` outside the nominal range).

`RangeError`

Thrown if there isn't enough memory available to allocate the buffer.

Examples
--------

 First, a couple of simple trivial examples, to help explain how the parameters are
 used:

```js
const audioCtx = new AudioContext();
const buffer = audioCtx.createBuffer(2, 22050, 44100);
```

 If you use this call, you will get a stereo buffer (two channels), that, when played
 back on an AudioContext running at 44100Hz (very common, most normal sound cards run at
 this rate), will last for 0.5 seconds: 22050 frames / 44100Hz = 0.5 seconds.

```js
const audioCtx = new AudioContext();
const buffer = audioCtx.createBuffer(1, 22050, 22050);
```

 If you use this call, you will get a mono buffer (one channel), that, when played back
 on an `AudioContext` running at 44100Hz, will be automatically \*resampled\* to
 44100Hz (and therefore yield 44100 frames), and last for 1.0 second: 44100 frames /
 44100Hz = 1 second.

**Note:** audio resampling is very similar to image resizing: say you've
 got a 16 x 16 image, but you want it to fill a 32x32 area: you resize (resample) it.
 the result has less quality (it can be blurry or edgy, depending on the resizing
 algorithm), but it works, and the resized image takes up less space. Resampled audio
 is exactly the same — you save space, but in practice you will be unable to properly
 reproduce high frequency content (treble sound).

 Now let's look at a more complex `createBuffer()` example, in which we
 create a three-second buffer, fill it with white noise, and then play it via an `AudioBufferSourceNode`. The comment should clearly explain what is going
 on. You can also run the code live, or view the source.

```js
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();

// Create an empty three-second stereo buffer at the sample rate of the AudioContext
const myArrayBuffer = audioCtx.createBuffer(
  2,
  audioCtx.sampleRate \* 3,
  audioCtx.sampleRate,
);

// Fill the buffer with white noise;
// just random values between -1.0 and 1.0
for (let channel = 0; channel < myArrayBuffer.numberOfChannels; channel++) {
  // This gives us the actual ArrayBuffer that contains the data
  const nowBuffering = myArrayBuffer.getChannelData(channel);
  for (let i = 0; i < myArrayBuffer.length; i++) {
    // Math.random() is in [0; 1.0]
    // audio needs to be in [-1.0; 1.0]
    nowBuffering[i] = Math.random() \* 2 - 1;
  }
}

// Get an AudioBufferSourceNode.
// This is the AudioNode to use when we want to play an AudioBuffer
const source = audioCtx.createBufferSource();
// set the buffer in the AudioBufferSourceNode
source.buffer = myArrayBuffer;
// connect the AudioBufferSourceNode to the
// destination so we can hear the sound
source.connect(audioCtx.destination);
// start the source playing
source.start();
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-createbuffer |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: createConvolver() method - Web APIs

BaseAudioContext: createConvolver() method
==========================================

 The `createConvolver()` method of the `BaseAudioContext`
 interface creates a `ConvolverNode`, which is commonly used to apply
 reverb effects to your audio. See the spec definition of Convolution for more information.

**Note:** The `ConvolverNode()`
 constructor is the recommended way to create a `ConvolverNode`; see
 Creating an AudioNode.

Syntax
------

```js
createConvolver()
```

### Parameters

None.

### Return value

A `ConvolverNode`.

Examples
--------

### Creating a convolver node

 The following example shows how to use an AudioContext to create a convolver node.
 You create an `AudioBuffer` containing a sound sample to be used
 as an ambience to shape the convolution (called the *impulse response*) and
 apply that to the convolver. The example below uses a short sample of a concert hall
 crowd, so the reverb effect applied is really deep and echoey.

For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js for the code that is excerpted below).

```js
const audioCtx = new AudioContext();
// ...

const convolver = audioCtx.createConvolver();
// ...

// Grab audio track via fetch() for convolver node
try {
  const response = await fetch(
    "https://mdn.github.io/voice-change-o-matic/audio/concert-crowd.ogg",
  );
  const arrayBuffer = await response.arrayBuffer();
  const decodedAudio = await audioCtx.decodeAudioData(arrayBuffer);
  convolver.buffer = decodedAudio;
} catch (error) {
  console.error(
    `Unable to fetch the audio file: ${name} Error: ${err.message}`,
  );
}
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-createconvolver |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: createGain() method - Web APIs

BaseAudioContext: createGain() method
=====================================

 The `createGain()` method of the `BaseAudioContext`
 interface creates a `GainNode`, which can be used to control the
 overall gain (or volume) of the audio graph.

**Note:** The `GainNode()`
 constructor is the recommended way to create a `GainNode`; see
 Creating an AudioNode.

Syntax
------

```js
createGain()
```

### Parameters

None.

### Return value

 A `GainNode` which takes as input one or more audio sources and outputs
 audio whose volume has been adjusted in gain (volume) to a level specified by the node's
 `GainNode.gain` a-rate
 parameter.

Examples
--------

 The following example shows basic usage of an `AudioContext` to create a
 `GainNode`, which is then used to mute and unmute the audio when a Mute
 button is clicked by changing the `gain` property value.

 The below snippet wouldn't work as is — for a complete working example, check out our
 Voice-change-O-matic demo (view source.)

```html
<div>
  <button class="mute">Mute button</button>
</div>
```

```js
const audioCtx = new AudioContext();
const gainNode = audioCtx.createGain();
const mute = document.querySelector(".mute");
let source;

if (navigator.mediaDevices.getUserMedia) {
  navigator.mediaDevices.getUserMedia(
    // constraints - only audio needed for this app
    {
      audio: true,
    },

    // Success callback
    (stream) => {
      source = audioCtx.createMediaStreamSource(stream);
    },

    // Error callback
    (err) => {
      console.error(`The following gUM error occurred: ${err}`);
    },
  );
} else {
  console.error("getUserMedia not supported on your browser!");
}

source.connect(gainNode);
gainNode.connect(audioCtx.destination);

// …

mute.onclick = () => {
  if (mute.id === "") {
    // 0 means mute. If you still hear something, make sure you haven't
    // connected your source into the output in addition to using the GainNode.
    gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
    mute.id = "activated";
    mute.textContent = "Unmute";
  } else {
    gainNode.gain.setValueAtTime(1, audioCtx.currentTime);
    mute.id = "";
    mute.textContent = "Mute";
  }
};
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-creategain |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: decodeAudioData() method - Web APIs

BaseAudioContext: decodeAudioData() method
==========================================

 The `decodeAudioData()` method of the `BaseAudioContext`
 Interface is used to asynchronously decode audio file data contained in an
 `ArrayBuffer` that is loaded from `fetch()`,
 `XMLHttpRequest`, or `FileReader`. The decoded
 `AudioBuffer` is resampled to the `AudioContext`'s sampling
 rate, then passed to a callback or promise.

 This is the preferred method of creating an audio source for Web Audio API from an
 audio track. This method only works on complete file data, not fragments of audio file
 data.

This function implements two alternative ways to asynchronously return the audio data or error messages: it returns a `Promise` that fulfills with the audio data, and also accepts callback arguments to handle success or failure. The primary method of interfacing with this function is via its Promise return value, and the callback parameters are provided for legacy reasons.

Syntax
------

```js
// Promise-based syntax returns a Promise:
decodeAudioData(arrayBuffer)

// Callback syntax has no return value:
decodeAudioData(arrayBuffer, successCallback)
decodeAudioData(arrayBuffer, successCallback, errorCallback)
```

### Parameters

`arrayBuffer`

 An ArrayBuffer containing the audio data to be decoded, usually grabbed from
 `fetch()`, `XMLHttpRequest` or `FileReader`.

`successCallback` Optional

 A callback function to be invoked when the decoding successfully finishes. The
 single argument to this callback is an `AudioBuffer` representing the
 *decodedData* (the decoded PCM audio data). Usually you'll want to put the
 decoded data into an `AudioBufferSourceNode`, from which it can be played
 and manipulated how you want.

`errorCallback` Optional

 An optional error callback, to be invoked if an error occurs when the audio data is
 being decoded.

### Return value

 A `Promise` object that fulfills with the *decodedData*. If you are using the
 XHR syntax you will ignore this return value and use a callback function instead.

Examples
--------

In this section we will first cover the promise-based syntax and then the callback syntax.

### Promise-based syntax

In this example `loadAudio()` uses `fetch()` to retrieve an audio file and decodes it into an `AudioBuffer`. It then caches the `audioBuffer` in the global `buffer` variable for later playback.

**Note:** You can run the full example live, or view the source.

```js
let audioCtx;
let buffer;
let source;

async function loadAudio() {
  try {
    // Load an audio file
    const response = await fetch("viper.mp3");
    // Decode it
    buffer = await audioCtx.decodeAudioData(await response.arrayBuffer());
  } catch (err) {
    console.error(`Unable to fetch the audio file. Error: ${err.message}`);
  }
}
```

### Callback syntax

 In this example `loadAudio()` uses `fetch()` to retrieve an audio
 file and decodes it into an `AudioBuffer` using the callback-based version of `decodeAudioData()`. In the callback, it plays the decoded buffer.

**Note:** You can run the full example live, or view the source.

```js
let audioCtx;
let source;

function playBuffer(buffer) {
  source = audioCtx.createBufferSource();
  source.buffer = buffer;
  source.connect(audioCtx.destination);
  source.loop = true;
  source.start();
}

async function loadAudio() {
  try {
    // Load an audio file
    const response = await fetch("viper.mp3");
    // Decode it
    audioCtx.decodeAudioData(await response.arrayBuffer(), playBuffer);
  } catch (err) {
    console.error(`Unable to fetch the audio file. Error: ${err.message}`);
  }
}
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-decodeaudiodata |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: createDelay() method - Web APIs

BaseAudioContext: createDelay() method
======================================

 The `createDelay()` method of the
 `BaseAudioContext` Interface is used to create a `DelayNode`,
 which is used to delay the incoming audio signal by a certain amount of time.

**Note:** The `DelayNode()`
 constructor is the recommended way to create a `DelayNode`; see
 Creating an AudioNode.

Syntax
------

```js
createDelay(maxDelayTime)
```

### Parameters

`maxDelayTime` Optional

 The maximum amount of time, in seconds, that the audio signal can be delayed by.
 Must be less than 180 seconds, and defaults to 1 second if not specified.

### Return value

 A `DelayNode`. The default `DelayNode.delayTime` is 0
 seconds.

Examples
--------

 We have created a simple example that allows you to play three different samples on a
 constant loop — see create-delay (you can also
 view the source code). If
 you just press the play buttons, the loops will start immediately; if you slide the
 sliders up to the right, then press the play buttons, a delay will be introduced, so the
 looping sounds don't start playing for a short amount of time.

```js
const audioCtx = new AudioContext();

const synthDelay = audioCtx.createDelay(5.0);

// …

let synthSource;

playSynth.onclick = () => {
  synthSource = audioCtx.createBufferSource();
  synthSource.buffer = buffers[2];
  synthSource.loop = true;
  synthSource.start();
  synthSource.connect(synthDelay);
  synthDelay.connect(destination);
  this.setAttribute("disabled", "disabled");
};

stopSynth.onclick = () => {
  synthSource.disconnect(synthDelay);
  synthDelay.disconnect(destination);
  synthSource.stop();
  playSynth.removeAttribute("disabled");
};

// …

let delay1;
rangeSynth.oninput = () => {
  delay1 = rangeSynth.value;
  synthDelay.delayTime.setValueAtTime(delay1, audioCtx.currentTime);
};
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-createdelay |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: statechange event - Web APIs

BaseAudioContext: statechange event
===================================

A `statechange` event is fired at a `BaseAudioContext` object when its `state` member changes.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("statechange", (event) => { })

onstatechange = (event) => { }
```

Event type
----------

A generic `Event`.

Examples
--------

 The following snippet is taken from our AudioContext states demo (see it running live.) The `onstatechange` handler is used to log the current
 `state` to the console every time it changes.

```js
audioCtx.onstatechange = () => {
  console.log(audioCtx.state);
};
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-onstatechange |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: listener property - Web APIs

BaseAudioContext: listener property
===================================

 The `listener` property of the `BaseAudioContext` interface
 returns an `AudioListener` object that can then be used for
 implementing 3D audio spatialization.

Value
-----

An `AudioListener` object.

Examples
--------

**Note:** for a full Web Audio spatialization example, see our panner-node demo.

```js
const audioCtx = new AudioContext();
// Older webkit/blink browsers require a prefix

// …

const myListener = audioCtx.listener;
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-listener |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: createScriptProcessor() method - Web APIs

BaseAudioContext: createScriptProcessor() method
================================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The `createScriptProcessor()` method of the `BaseAudioContext` interface
 creates a `ScriptProcessorNode` used for direct audio processing.

**Note:** This feature was replaced by AudioWorklets and the `AudioWorkletNode` interface.

Syntax
------

```js
createScriptProcessor(bufferSize, numberOfInputChannels, numberOfOutputChannels)
```

### Parameters

`bufferSize`

 The buffer size in units of sample-frames. If specified, the bufferSize must be one
 of the following values: 256, 512, 1024, 2048, 4096, 8192, 16384. 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 a constant power of 2 throughout the lifetime of
 the node.

 This value controls how frequently the `audioprocess` event is dispatched
 and how many sample-frames need to be processed each call. Lower values for
 `bufferSize` will result in a lower (better) latency. Higher values will be
 necessary to avoid audio breakup and glitches. It is recommended for authors to not
 specify this buffer size and allow the implementation to pick a good buffer size to
 balance between latency and audio quality.

`numberOfInputChannels`

 Integer specifying the number of channels for this node's input, defaults to 2.
 Values of up to 32 are supported.

`numberOfOutputChannels`

 Integer specifying the number of channels for this node's output, defaults to 2.
 Values of up to 32 are supported.

**Warning:** Webkit currently (version 31) requires that a valid
 `bufferSize` be passed when calling this method.

**Note:** It is invalid for both `numberOfInputChannels` and
 `numberOfOutputChannels` to be zero.

### Return value

A `ScriptProcessorNode`.

Examples
--------

### Adding white noise using a script processor

The following example shows how to use a `ScriptProcessorNode` to take a track loaded via `AudioContext.decodeAudioData()`, process it, adding a bit of white noise to each audio sample of the input track, and play it through the `AudioDestinationNode`.

For each channel and each sample frame, the script node's `audioprocess` event handler uses the associated `audioProcessingEvent` to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case.

**Note:** You can run the full example live, or view the source.

```js
const myScript = document.querySelector("script");
const myPre = document.querySelector("pre");
const playButton = document.querySelector("button");

// Create AudioContext and buffer source
let audioCtx;

async function init() {
  audioCtx = new AudioContext();
  const source = audioCtx.createBufferSource();

  // Create a ScriptProcessorNode with a bufferSize of 4096 and
  // a single input and output channel
  const scriptNode = audioCtx.createScriptProcessor(4096, 1, 1);

  // Load in an audio track using fetch() and decodeAudioData()
  try {
    const response = await fetch("viper.ogg");
    const arrayBuffer = await response.arrayBuffer();
    source.buffer = await audioCtx.decodeAudioData(arrayBuffer);
  } catch (err) {
    console.error(
      `Unable to fetch the audio file: ${name} Error: ${err.message}`,
    );
  }

  // Give the node a function to process audio events
  scriptNode.addEventListener("audioprocess", (audioProcessingEvent) => {
    // The input buffer is the song we loaded earlier
    let inputBuffer = audioProcessingEvent.inputBuffer;

    // The output buffer contains the samples that will be modified and played
    let outputBuffer = audioProcessingEvent.outputBuffer;

    // Loop through the output channels (in this case there is only one)
    for (let channel = 0; channel < outputBuffer.numberOfChannels; channel++) {
      let inputData = inputBuffer.getChannelData(channel);
      let outputData = outputBuffer.getChannelData(channel);

      // Loop through the 4096 samples
      for (let sample = 0; sample < inputBuffer.length; sample++) {
        // make output equal to the same as the input
        outputData[sample] = inputData[sample];

        // add noise to each output sample
        outputData[sample] += (Math.random() \* 2 - 1) \* 0.1;
      }
    }
  });

  source.connect(scriptNode);
  scriptNode.connect(audioCtx.destination);
  source.start();

  // When the buffer source stops playing, disconnect everything
  source.addEventListener("ended", () => {
    source.disconnect(scriptNode);
    scriptNode.disconnect(audioCtx.destination);
  });
}

// wire up play button
playButton.addEventListener("click", () => {
  if (!audioCtx) {
    init();
  }
});
```

Specifications
--------------

Since the August 29 2014 Web Audio API specification publication, this feature has been deprecated. It is no longer on track to become a standard.

It was replaced by AudioWorklets and the `AudioWorkletNode` interface.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: audioWorklet property - Web APIs

BaseAudioContext: audioWorklet property
=======================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

 The `audioWorklet` read-only property of the
 `BaseAudioContext` interface returns an instance of
 `AudioWorklet` that can be used for adding
 `AudioWorkletProcessor`-derived classes which implement custom audio
 processing.

Value
-----

An `AudioWorklet` instance.

Examples
--------

*For a complete example demonstrating user-defined audio processing, see the
`AudioWorkletNode` page.*

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-audioworklet |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using Web Audio API
* `AudioWorkletNode`


BaseAudioContext: createStereoPanner() method - Web APIs

BaseAudioContext: createStereoPanner() method
=============================================

 The `createStereoPanner()` method of the `BaseAudioContext` interface creates a `StereoPannerNode`, which can be used to apply
 stereo panning to an audio source.
 It positions an incoming audio stream in a stereo image using a low-cost panning algorithm.

**Note:** The `StereoPannerNode()`
 constructor is the recommended way to create a `StereoPannerNode`; see
 Creating an AudioNode.

Syntax
------

```js
createStereoPanner()
```

### Parameters

None.

### Return value

A `StereoPannerNode`.

Examples
--------

 In our StereoPannerNode example (see source code) HTML we have a simple `<audio>` element along with a
 slider `<input>` to increase and decrease pan value. In the JavaScript we
 create a `MediaElementAudioSourceNode` and a
 `StereoPannerNode`, and connect the two together using the
 `connect()` method. We then use an `oninput` event handler to
 change the value of the `StereoPannerNode.pan` parameter and update the pan
 value display when the slider is moved.

 Moving the slider left and right while the music is playing pans the music across to
 the left and right speakers of the output, respectively.

```js
const audioCtx = new AudioContext();
const myAudio = document.querySelector("audio");

const panControl = document.querySelector(".panning-control");
const panValue = document.querySelector(".panning-value");

// Create a MediaElementAudioSourceNode
// Feed the HTMLMediaElement into it
const source = audioCtx.createMediaElementSource(myAudio);

// Create a stereo panner
const panNode = audioCtx.createStereoPanner();

// Event handler function to increase panning to the right and left
// when the slider is moved

panControl.oninput = () => {
  panNode.pan.setValueAtTime(panControl.value, audioCtx.currentTime);
  panValue.innerHTML = panControl.value;
};

// connect the MediaElementAudioSourceNode to the panNode
// and the panNode to the destination, so we can play the
// music and adjust the panning using the controls
source.connect(panNode);
panNode.connect(audioCtx.destination);
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-createstereopanner |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: destination property - Web APIs

BaseAudioContext: destination property
======================================

 The `destination` property of the `BaseAudioContext`
 interface returns an `AudioDestinationNode` representing the final
 destination of all audio in the context. It often represents an actual audio-rendering
 device such as your device's speakers.

Value
-----

An `AudioDestinationNode`.

Examples
--------

**Note:** For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 108–193 for relevant code).

```js
const audioCtx = new AudioContext();
// Older webkit/blink browsers require a prefix

const oscillatorNode = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();

oscillatorNode.connect(gainNode);
gainNode.connect(audioCtx.destination);
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-destination |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BaseAudioContext: sampleRate property - Web APIs

BaseAudioContext: sampleRate property
=====================================

 The `sampleRate` property of the `BaseAudioContext` interface returns a floating point number representing
 the sample rate, in samples per second, used by all nodes in this audio
 context. This limitation means that sample-rate converters are not supported.

Value
-----

 A floating point number indicating the audio context's sample rate, in samples per
 second.

Examples
--------

**Note:** for a full Web Audio example implementation, see one of our
 Web Audio Demos on the MDN GitHub repo. Try entering
 `audioCtx.sampleRate` into your browser console.

```js
const audioCtx = new AudioContext();
// Older webkit/blink browsers require a prefix

// …

console.log(audioCtx.sampleRate);
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-baseaudiocontext-samplerate |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


DOMPoint: fromPoint() static method - Web APIs

DOMPoint: fromPoint() static method
===================================

 The **`DOMPoint`** static method
 `fromPoint()` creates and returns a new mutable `DOMPoint`
 object given a source point.

 You can also create a new `DOMPoint` object using the
 `new DOMPoint()` constructor.

 Although this interface is based on `DOMPointReadOnly`, it is not read-only;
 the properties within may be changed at will.

Syntax
------

```js
DOMPoint.fromPoint(sourcePoint)
```

### Parameters

`sourcePoint`

 A `DOMPoint` or `DOMPointReadOnly` instance, or an object containing the following properties, from which to take the
 values of the new point's properties:

`x`

An unrestricted floating-point value indicating the `x`-coordinate of the point in space. This is generally the horizontal coordinate, with positive values being to the right and negative values to the left. The default value is `0`.

`y`

An unrestricted floating-point number providing the point's `y`-coordinate. This is the vertical coordinate, and barring any transforms applied to the coordinate system, positive values are downward and negative values upward toward the top of the screen. The default is `0`.

`z`

An unrestricted floating-point value which gives the point's `z`-coordinate, which is (assuming no transformations that alter the situation) the depth coordinate; positive values are closer to the user and negative values retreat back into the screen. The default value is `0`.

`w`

The point's `w` perspective value, given as an unrestricted floating-point number. The default is `1`.

### Return value

 A new `DOMPoint` object whose coordinate and perspective values are
 identical to those in the source point. The point's properties are mutable and may be
 changed at any time.

Examples
--------

### Creating a mutable point from a read-only point

 If you have a `DOMPointReadOnly` object, you can easily create a mutable
 copy of that point:

```js
const mutablePoint = DOMPoint.fromPoint(readOnlyPoint);
```

### Creating a 2D point

 This sample creates a 2D point, specifying an inline object that includes the values to
 use for `x` and `y`. The *z* and *w* properties are allowed to keep their default
 values (0 and 1 respectively).

```js
const center = DOMPoint.fromPoint({ x: 75, y: -50, z: -55, w: 0.25 });
```

Specifications
--------------

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-dompoint-frompoint |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


DOMPoint: w property - Web APIs

DOMPoint: w property
====================

 The **`DOMPoint`** interface's
 **`w`** property holds the point's perspective value, w, for a
 point in space.

Value
-----

 A double-precision floating-point value indicating the *w* perspective value for
 the point. This value is **unrestricted**, meaning that it is allowed to be
 infinite or invalid (that is, its value may be `NaN` or `±Infinity`). The default is 1.0.

Specifications
--------------

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-dompointreadonly-w |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The other coordinate properties: `x`,
 `y`, and `z`.


DOMPoint: z property - Web APIs

DOMPoint: z property
====================

 The **`DOMPoint`** interface's
 **`z`** property specifies the depth coordinate of a point in
 space.

 Unless transforms have changed the orientation, a `z` of 0 is
 the plane of the screen, with positive values extending outward toward the user from the
 screen, and negative values receding into the distance behind the screen.

Value
-----

 A double-precision floating-point value indicating the *z* coordinate's value
 for the point. This value is **unrestricted**, meaning that it is allowed
 to be infinite or invalid (that is, its value may be `NaN` or
 `±Infinity`).

Specifications
--------------

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-dompointreadonly-z |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The other coordinate properties: `x`,
 `y`, and the perspective value, `w`.


DOMPoint: DOMPoint() constructor - Web APIs

DOMPoint: DOMPoint() constructor
================================

 The **`DOMPoint()`** constructor
 creates and returns a new `DOMPoint` object, given the values for some or
 all of its properties.

 You can also create a `DOMPoint` by calling the
 `DOMPoint.fromPoint()` static function. That function accepts any object with the required parameters, including a `DOMPoint` or
 `DOMPointReadOnly`.

Syntax
------

```js
new DOMPoint()
new DOMPoint(x)
new DOMPoint(x, y)
new DOMPoint(x, y, z)
new DOMPoint(x, y, z, w)
```

### Parameters

`x` Optional

The `x` coordinate for the new `DOMPoint`.

`y` Optional

The `y` coordinate for the new `DOMPoint`.

`z` Optional

The `z` coordinate for the new `DOMPoint`.

`w` Optional

The perspective value of the new `DOMPoint`.

Examples
--------

 This example creates a `DOMPoint` representing the top-left corner of the
 current window, then creates a second point based on the first, which is then offset by
 100 pixels both vertically and horizontally.

```js
const windTopLeft = new DOMPoint(window.screenX, window.screenY);
const newTopLeft = DOMPoint.fromPoint(windTopLeft);
newTopLeft.x += 100;
newTopLeft.y += 100;
```

Specifications
--------------

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-dompoint-dompoint |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `DOMPointReadOnly()`
* `DOMRect`
* `DOMMatrix`


DOMPoint: x property - Web APIs

DOMPoint: x property
====================

 The **`DOMPoint`** interface's
 **`x`** property holds the horizontal coordinate, x, for a
 point in space.

 In general, positive values `x` mean to the right,
 and negative values of `x` means to the left, barring any transforms that may
 have altered the orientation of the axes.

Value
-----

 A double-precision floating-point value indicating the x coordinate's value for the
 point. This value is **unrestricted**, meaning that it is allowed to be
 infinite or invalid (that is, its value may be `NaN` or `±Infinity`).

Specifications
--------------

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-dompointreadonly-x |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The other coordinate properties: `y`,
 `z`, and the perspective value, `w`.


DOMPoint: y property - Web APIs

DOMPoint: y property
====================

 The **`DOMPoint`** interface's
 **`y`** property holds the vertical coordinate, *y*,
 for a point in space.

 Unless transforms have been applied to alter the
 orientation, the value of `y` increases downward and decreases upward.

Value
-----

 A double-precision floating-point value indicating the *y* coordinate's value
 for the point. This value is **unrestricted**, meaning that it is allowed
 to be infinite or invalid (that is, its value may be `NaN` or
 `±Infinity`).

Specifications
--------------

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-dompointreadonly-y |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The other coordinate properties: `x`,
 `z`, and the perspective value, `w`.


XRQuadLayer: space property - Web APIs

XRQuadLayer: space property
===========================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`space`** property of the `XRQuadLayer` interface represents the layer's spatial relationship with the user's physical environment.

Value
-----

An `XRSpace`.

Examples
--------

### Setting a layer's dimension and position

This example code positions the layer two meters away from `newSpace` with a `height` and `width` of 1.5 meters.

```js
const quadLayer = xrGlBinding.createQuadLayer({
  space: xrReferenceSpace,
  viewPixelWidth: 512,
  viewPixelHeight: 512,
});

quadLayer.space = newSpace;
quadLayer.transform = new XRRigidTransform({ z: -2 });
quadLayer.width = 1.5;
quadLayer.height = 1.5;
```

Specifications
--------------

| Specification |
| --- |
| WebXR Layers API Level 1 # dom-xrquadlayer-space |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `XRSpace`
* `XRQuadLayer.transform`


XRQuadLayer: width property - Web APIs

XRQuadLayer: width property
===========================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`width`** property of the `XRQuadLayer` interface represents the width of the layer in meters.

Value
-----

A number representing the width of the layer in meters.

Examples
--------

### Setting a layer's dimension and position

This example code positions the layer two meters away from the origin of `xrReferenceSpace` with a `height` and `width` of 1.5 meters.

```js
const quadLayer = xrGlBinding.createQuadLayer({
  space: xrReferenceSpace,
  viewPixelWidth: 512,
  viewPixelHeight: 512,
});

quadLayer.transform = new XRRigidTransform({ z: -2 });
quadLayer.width = 1.5;
quadLayer.height = 1.5;
```

Specifications
--------------

| Specification |
| --- |
| WebXR Layers API Level 1 # dom-xrquadlayer-width |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `XRQuadLayer.height`


XRQuadLayer: transform property - Web APIs

XRQuadLayer: transform property
===============================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`transform`** property of the `XRQuadLayer` interface represents the offset and orientation relative to the layer's `space`.

Value
-----

An `XRRigidTransform`.

Examples
--------

### Setting a layer's dimension and position

This example code positions the layer two meters away from the origin of `xrReferenceSpace` with a `height` and `width` of 1.5 meters.

```js
const quadLayer = xrGlBinding.createQuadLayer({
  space: xrReferenceSpace,
  viewPixelWidth: 512,
  viewPixelHeight: 512,
});

quadLayer.transform = new XRRigidTransform({ z: -2 });
quadLayer.width = 1.5;
quadLayer.height = 1.5;
```

Specifications
--------------

| Specification |
| --- |
| WebXR Layers API Level 1 # dom-xrquadlayer-transform |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `XRRigidTransform`
* `XRQuadLayer.space`


XRQuadLayer: height property - Web APIs

XRQuadLayer: height property
============================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`height`** property of the `XRQuadLayer` interface represents the height of the layer in meters.

Value
-----

A number representing the height of the layer in meters.

Examples
--------

### Setting a layer's dimension and position

This example code positions the layer two meters away from the origin of `xrReferenceSpace` with a `height` and `width` of 1.5 meters.

```js
const quadLayer = xrGlBinding.createQuadLayer({
  space: xrReferenceSpace,
  viewPixelWidth: 512,
  viewPixelHeight: 512,
});

quadLayer.transform = new XRRigidTransform({ z: -2 });
quadLayer.width = 1.5;
quadLayer.height = 1.5;
```

Specifications
--------------

| Specification |
| --- |
| WebXR Layers API Level 1 # dom-xrquadlayer-height |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `XRQuadLayer.width`


XRQuadLayer: redraw event - Web APIs

XRQuadLayer: redraw event
=========================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The `redraw` event is sent to the `XRQuadLayer` object when the underlying resources of the layer are lost or when the XR Compositor can no longer reproject the layer. If this event is sent, authors should redraw the content of the layer in the next XR animation frame.

See also the `XRCompositionLayer.needsRedraw` property which is also available to `XRQuadLayer` objects through inheritance from `XRCompositionLayer`.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("redraw", (event) => {});

onredraw = (event) => {};
```

Event type
----------

An `XRLayerEvent`. Inherits from `Event`.

Event properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`layer` Read only

The `XRLayer` which generated the event.

Examples
--------

### Using the `redraw` event

You can pass `redraw` to `addEventListener()`:

```js
quadLayer.addEventListener("redraw", (event) => {
  // redraw the layer
});
```

Alternatively, you can use the `onredraw` event handler property to establish a handler for the `redraw` event:

```js
quadLayer.onredraw = (event) => {
  // redraw the layer
};
```

Specifications
--------------

| Specification |
| --- |
| WebXR Layers API Level 1 # eventdef-xrlayer-redraw |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `XRCompositionLayer.needsRedraw`


AuthenticatorAssertionResponse: signature property - Web APIs

AuthenticatorAssertionResponse: signature property
==================================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

 The **`signature`** read-only property of the
 `AuthenticatorAssertionResponse` interface is an `ArrayBuffer`
 object which is the signature of the authenticator for both
 `AuthenticatorAssertionResponse.authenticatorData` and a SHA-256 hash of
 the client data
 (`AuthenticatorAssertionResponse.clientDataJSON`).

 This signature will be sent to the server for control, as part of the response. It
 provides the proof that an authenticator does possess the private key which was used for
 the credential's generation.

Value
-----

 An `ArrayBuffer` object which the signature of the authenticator (using its
 private key) for both `AuthenticatorAssertionResponse.authenticatorData`
 and a SHA-256 hash given by the client for its data (the challenge, the origin, etc. and
 available from
 `AuthenticatorAssertionResponse.clientDataJSON`).

Examples
--------

See User login using the WebAuthn API for a detailed example.

Specifications
--------------

| Specification |
| --- |
| Web Authentication: An API for accessing Public Key Credentials - Level 3 # dom-authenticatorassertionresponse-signature |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


AuthenticatorAssertionResponse: authenticatorData property - Web APIs

AuthenticatorAssertionResponse: authenticatorData property
==========================================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **`authenticatorData`** property of the `AuthenticatorAssertionResponse` interface returns an `ArrayBuffer` containing information from the authenticator such as the Relying Party ID Hash (rpIdHash), a signature counter, test of user presence, user verification flags, and any extensions processed by the authenticator.

Value
-----

An `ArrayBuffer` with a `ArrayBuffer.byteLength` of at least 37 bytes, which contains the data structure explained in Authenticator data.

Examples
--------

See User login using the WebAuthn API for a detailed example.

Specifications
--------------

| Specification |
| --- |
| Web Authentication: An API for accessing Public Key Credentials - Level 3 # dom-authenticatorassertionresponse-authenticatordata |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


AuthenticatorAssertionResponse: userHandle property - Web APIs

AuthenticatorAssertionResponse: userHandle property
===================================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **`userHandle`** read-only property of the `AuthenticatorAssertionResponse` interface is an `ArrayBuffer` object providing an opaque identifier for the given user. Such an identifier can be used by the relying party's server to link the user account with its corresponding credentials and other data.

This value is specified as `user.id` in the options passed to the originating `navigator.credentials.create()` call.

Value
-----

An `ArrayBuffer` object representing an identifier for the current user. This is not intended to be human-readable. The relying party should make sure that the `user.id` passed into the originating `create()` call does **not** contain any personally identifying information (for example user name, email, or phone number).

For `navigator.credentials.create()` calls made with a non-empty `allowCredentials` properties, the returned `userHandle` may be null.

Examples
--------

See User login using the WebAuthn API for a detailed example.

Specifications
--------------

| Specification |
| --- |
| Web Authentication: An API for accessing Public Key Credentials - Level 3 # dom-authenticatorassertionresponse-userhandle |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `CredentialsContainer.create()` that sets the value of this property


OES_draw_buffers_indexed: blendFuncSeparateiOES() method - Web APIs

OES\_draw\_buffers\_indexed: blendFuncSeparateiOES() method
===========================================================

The `blendFuncSeparateiOES()` method of the `OES_draw_buffers_indexed` WebGL extension defines which function is used when blending pixels for RGB and alpha components separately for a particular draw buffer.

See `OES_draw_buffers_indexed.blendFunciOES()` for setting RGB and alpha together and `WebGLRenderingContext.blendFuncSeparate()` for the WebGL 1 version of this method.

Syntax
------

```js
blendFuncSeparateiOES(buf, srcRGB, dstRGB, srcAlpha, dstAlpha)
```

### Parameters

`buf`

An integer `i` specifying the draw buffer associated with the constant `gl.DRAW_BUFFERi`, see WebGL draw buffer constants.

`srcRGB`

A `GLenum` specifying a multiplier for the red, green and blue (RGB) source blending factors. Accepts the same enums as the `srcRGB` parameter in `WebGLRenderingContext.blendFuncSeparate()`.

`dstRGB`

A `GLenum` specifying a multiplier for the red, green and blue (RGB) destination blending factors. Accepts the same enums as the `dstRGB` parameter in `WebGLRenderingContext.blendFuncSeparate()`.

`srcAlpha`

A `GLenum` specifying a multiplier for the alpha source blending factor. Accepts the same enums as the `srcAlpha` parameter in `WebGLRenderingContext.blendFuncSeparate()`.

`dstAlpha`

A `GLenum` specifying a multiplier for the alpha destination blending factor. Accepts the same enums as the `srcAlpha` parameter in `WebGLRenderingContext.blendFuncSeparate()`.

### Return value

None (`undefined`).

### Exceptions

* If `buf` is not a valid value, a `gl.INVALID_VALUE` error is thrown.
* If `srcRGB`, `dstRGB`, `srcAlpha` or `dstAlpha` are not one of the possible values, a `gl.INVALID_ENUM` error is thrown.
* The same blending limitations as for `WebGLRenderingContext.blendFuncSeparate()` apply: If a constant color and a constant alpha value are used together as source and destination factors, a `gl.INVALID_ENUM` error is thrown.
Examples
--------

### Setting and getting blend functions

The following sets the blend functions for the draw buffers `gl.DRAW_BUFFER0` (call where `buf` is 0) and `gl.DRAW_BUFFER1` (call where `buf` is 1).

```js
const ext = gl.getExtension("OES\_draw\_buffers\_indexed");

ext.blendFuncSeparateiOES(0, gl.ONE, gl.ONE, gl.ZERO, gl.ZERO);
ext.blendFuncSeparateiOES(
  1,
  gl.SRC\_ALPHA,
  gl.ONE\_MINUS\_SRC\_ALPHA,
  gl.ZERO,
  gl.ZERO,
);
```

To get the blend functions for the `gl.DRAW_BUFFER0` and `gl.DRAW_BUFFER1` draw buffers, query the `BLEND_SRC_RGB`, `BLEND_SRC_ALPHA`, `BLEND_DST_RGB`, and `BLEND_DST_ALPHA` constants using `WebGL2RenderingContext.getIndexedParameter()`:

```js
// For gl.DRAW\_BUFFER0
gl.getIndexedParameter(gl.BLEND\_SRC\_RGB, 0);
gl.getIndexedParameter(gl.BLEND\_SRC\_ALPHA, 0);
gl.getIndexedParameter(gl.BLEND\_DST\_RGB, 0);
gl.getIndexedParameter(gl.BLEND\_DST\_ALPHA, 0);

// For gl.DRAW\_BUFFER0
gl.getIndexedParameter(gl.BLEND\_SRC\_RGB, 1);
gl.getIndexedParameter(gl.BLEND\_SRC\_ALPHA, 1);
gl.getIndexedParameter(gl.BLEND\_DST\_RGB, 1);
gl.getIndexedParameter(gl.BLEND\_DST\_ALPHA, 1);
```

Specifications
--------------

| Specification |
| --- |
| WebGL OES\_draw\_buffers\_indexed Extension Specification  |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `OES_draw_buffers_indexed.blendFunciOES()`
* `WebGLRenderingContext.blendFuncSeparate()`


OES_draw_buffers_indexed: colorMaskiOES() method - Web APIs

OES\_draw\_buffers\_indexed: colorMaskiOES() method
===================================================

The `colorMaskiOES()` method of the `OES_draw_buffers_indexed` WebGL extension sets which color components to enable or to disable when drawing or rendering for a particular draw buffer. It's the indexed version of WebGL 1's `WebGLRenderingContext.colorMask()` method.

Syntax
------

```js
colorMaskiOES(buf, r, g, b, a)
```

### Parameters

`buf`

An integer `i` specifying the draw buffer associated with the constant `gl.DRAW_BUFFERi`, see WebGL draw buffer constants.

`r`

A `GLboolean` specifying whether or not the red color component should be written into the draw buffer.

`g`

A `GLboolean` specifying whether or not the green color component should be written into the draw buffer.

`b`

A `GLboolean` specifying whether or not the blue color component should be written into the draw buffer.

`a`

A `GLboolean` specifying whether or not the red alpha (transparency) component should be written into the draw buffer.

### Return value

None (`undefined`).

### Exceptions

* If `buf`, `r`, `b`, `g`, or `a` are not a valid values, a `gl.INVALID_VALUE` error is thrown.
Examples
--------

### Setting and getting color masks

You can set the color masks for the `gl.DRAW_BUFFER0` and `gl.DRAW_BUFFER1` draw buffers like this:

```js
const ext = gl.getExtension("OES\_draw\_buffers\_indexed");

ext.colorMaskiOES(0, 1, 0, 0, 0);
ext.colorMaskiOES(1, 0, 1, 0, 0);
```

To get the color masks for the `gl.DRAW_BUFFER0` and `gl.DRAW_BUFFER1` draw buffers, query the `COLOR_WRITEMASK` constant using `WebGL2RenderingContext.getIndexedParameter()`:

```js
gl.getIndexedParameter(gl.COLOR\_WRITEMASK, 0);
gl.getIndexedParameter(gl.COLOR\_WRITEMASK, 1);
```

Specifications
--------------

| Specification |
| --- |
| WebGL OES\_draw\_buffers\_indexed Extension Specification  |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `WebGL2RenderingContext.getIndexedParameter()`
* `WebGLRenderingContext.colorMask()`


OES_draw_buffers_indexed: disableiOES() method - Web APIs

OES\_draw\_buffers\_indexed: disableiOES() method
=================================================

The `disableiOES()` method of the `OES_draw_buffers_indexed` WebGL extension enables blending for a particular draw buffer.

Syntax
------

```js
disableiOES(target, index)
```

### Parameters

`target`

Must be `gl.BLEND`.

`index`

An integer `i` specifying the draw buffer associated with the constant `gl.DRAW_BUFFERi`, see WebGL draw buffer constants.

### Return value

None (`undefined`).

### Exceptions

* If `target` is not `gl.BLEND`, a `gl.INVALID_ENUM` error is thrown.
* If `index` is not a valid value, a `gl.INVALID_VALUE` error is thrown.
Examples
--------

### Disabling blending for draw buffers

The following two calls disable blending for the draw buffers `gl.DRAW_BUFFER0` and `gl.DRAW_BUFFER1`.

```js
const ext = gl.getExtension("OES\_draw\_buffers\_indexed");

ext.disableiOES(gl.BLEND, 0);
ext.disableiOES(gl.BLEND, 1);
```

Specifications
--------------

| Specification |
| --- |
| WebGL OES\_draw\_buffers\_indexed Extension Specification  |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `OES_draw_buffers_indexed.enableiOES()`
* WebGL draw buffer constants