recursal/MDN huggingface dataset:
AudioContext: createMediaElementSource() method
===============================================

The `createMediaElementSource()` method of the `AudioContext` Interface is used to create a new `MediaElementAudioSourceNode` object, given an existing HTML `<audio>` or `<video>` element, the audio from which can then be played and manipulated.

For more details about media element audio source nodes, check out the `MediaElementAudioSourceNode` reference page.

Syntax
------


```js
createMediaElementSource(myMediaElement)
```

### Parameters

`myMediaElement`

An `HTMLMediaElement` object that you want to feed into an audio processing graph to manipulate.

### Return value

A `MediaElementAudioSourceNode`.

Examples
--------

This simple example creates a source from an `<audio>` element using `createMediaElementSource()`, then passes the audio through a `GainNode` before feeding it into the `AudioDestinationNode` for playback. When the mouse pointer is moved, the `updatePage()` function is invoked, which calculates the current gain as a ratio of mouse Y position divided by overall window height. You can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down.

**Note:** You can also view this example running live, or view the source.


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

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

// Create a gain node
const gainNode = audioCtx.createGain();

// Create variables to store mouse pointer Y coordinate
// and HEIGHT of screen
let curY;
const HEIGHT = window.innerHeight;

// Get new mouse pointer coordinates when mouse is moved
// then set new gain value
document.onmousemove = updatePage;

function updatePage(e) {
  curY = e.pageY;
  gainNode.gain.value = curY / HEIGHT;
}

// Connect the AudioBufferSourceNode to the gainNode
// and the gainNode to the destination, so we can play the
// music and adjust the volume using the mouse cursor
source.connect(gainNode);
gainNode.connect(audioCtx.destination);
```


**Note:** As a consequence of calling `createMediaElementSource()`, audio playback from the `HTMLMediaElement` will be re-routed into the processing graph of the AudioContext. So playing/pausing the media can still be done through the media element API and the player controls.

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

| Specification |
| --- |
| Web Audio API # dom-audiocontext-createmediaelementsource |

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

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

See also
--------

* Using the Web Audio API
AudioContext: close() method
============================

The `close()` method of the `AudioContext` Interface closes the audio context, releasing any system audio resources that it uses.

This function does not automatically release all `AudioContext`-created objects, unless other references have been released as well; however, it will forcibly release any system audio resources that might prevent additional `AudioContexts` from being created and used, suspend the progression of audio time in the audio context, and stop processing audio data. The returned `Promise` resolves when all `AudioContext`-creation-blocking resources have been released. This method throws an `INVALID_STATE_ERR` exception if called on an `OfflineAudioContext`.

Syntax
------


```js
close()
```

### Parameters

None.

### Return value

A `Promise` that resolves with `undefined`.

Examples
--------

The following snippet is taken from our AudioContext states demo (see it running live.) When the stop button is clicked, `close()` is called. When the promise resolves, the example is reset to its beginning state.


```js
stopBtn.onclick = () => {
  audioCtx.close().then(() => {
    startBtn.removeAttribute("disabled");
    susresBtn.setAttribute("disabled", "disabled");
    stopBtn.setAttribute("disabled", "disabled");
  });
};
```

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

| Specification |
| --- |
| Web Audio API # dom-audiocontext-close |

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

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

See also
--------

* Using the Web Audio API
* Web Audio API
AudioContext: sinkchange event
==============================

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

The **`sinkchange`** event of the `AudioContext` interface is fired when the output audio device (and therefore, the `AudioContext.sinkId`) has changed.

Syntax
------

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


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

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

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

`Event`.

Examples
--------

A `sinkchange` event listener can be used to report a change of audio output device. Note that if `sinkId` contains an `AudioSinkInfo` object, it indicates that the audio has been changed to not play on any output device.


```js
audioCtx.addEventListener("sinkchange", () => {
  if (typeof audioCtx.sinkId === "object" && audioCtx.sinkId.type === "none") {
    console.log("Audio changed to not play on any device");
  } else {
    console.log(`Audio output device changed to ${audioCtx.sinkId}`);
  }
});
```


See our SetSinkId test example for working code.

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

| Specification |
| --- |
| Web Audio API # eventdef-audiocontext-sinkchange |

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

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

See also
--------

* SetSinkId test example
* Change the destination output device in Web Audio
* `AudioContext.setSinkId()`
* `AudioContext.sinkId`
AudioContext: createMediaStreamTrackSource() method
===================================================

 The **`createMediaStreamTrackSource()`** method of the `AudioContext` interface creates and returns a
 `MediaStreamTrackAudioSourceNode` which represents an audio source whose
 data comes from the specified `MediaStreamTrack`.

 This differs from `createMediaStreamSource()`, which creates a
 `MediaStreamAudioSourceNode` whose audio comes from the audio track in a
 specified `MediaStream` whose `id` is
 first, lexicographically (alphabetically).

Syntax
------


```js
createMediaStreamTrackSource(track)
```

### Parameters

`track`

 The `MediaStreamTrack` to use as the source of all audio data for the
 new node.


### Return value

 A `MediaStreamTrackAudioSourceNode` object which acts as a source for
 audio data found in the specified audio track.

Examples
--------

 In this example, `getUserMedia()` is used to
 request access to the user's microphone. Once that access is attained, an audio context
 is established and a `MediaStreamTrackAudioSourceNode` is created using
 `createMediaStreamTrackSource()`, taking its audio from the first audio track
 in the stream returned by `getUserMedia()`.

 Then a `BiquadFilterNode` is created using
 `createBiquadFilter()`, and it's
 configured as desired to perform a lowshelf filter on the audio coming from the source.
 The output from the microphone is then routed into the new biquad filter, and the
 filter's output is in turn routed to the audio context's
 `destination`.


```js
navigator.mediaDevices
  .getUserMedia({ audio: true, video: false })
  .then((stream) => {
    audio.srcObject = stream;
    audio.onloadedmetadata = (e) => {
      audio.play();
      audio.muted = true;
    };

    const audioCtx = new AudioContext();
    const audioTracks = stream.getAudioTracks();
    const source = audioCtx.createMediaStreamTrackSource(audioTracks[0]);

    const biquadFilter = audioCtx.createBiquadFilter();
    biquadFilter.type = "lowshelf";
    biquadFilter.frequency.value = 3000;
    biquadFilter.gain.value = 20;

    source.connect(biquadFilter);
    biquadFilter.connect(audioCtx.destination);
  })
  .catch((err) => {
    // Handle getUserMedia() error
  });
```

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

| Specification |
| --- |
| Web Audio API # dom-audiocontext-createmediastreamtracksource |

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

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

See also
--------

* Web Audio API
* Using the Web Audio API
* `MediaStreamTrackAudioSourceNode`
AudioContext: suspend() method
==============================

The `suspend()` method of the `AudioContext` Interface suspends the progression of time in the audio context, temporarily halting audio hardware access and reducing CPU/battery usage in the process — this is useful if you want an application to power down the audio hardware when it will not be using an audio context for a while.

This method will cause an `INVALID_STATE_ERR` exception to be thrown if called on an `OfflineAudioContext`.

Syntax
------


```js
suspend()
```

### Parameters

None.

### Return value

A `Promise` that resolves with `undefined`. The promise is rejected if the context has already been closed.

Examples
--------

The following snippet is taken from our AudioContext states demo (see it running live.) When the suspend/resume button is clicked, the `AudioContext.state` is queried — if it is `running`, `suspend()` is called; if it is `suspended`, `resume()` is called. In each case, the text label of the button is updated as appropriate once the promise resolves.


```js
susresBtn.onclick = () => {
  if (audioCtx.state === "running") {
    audioCtx.suspend().then(() => {
      susresBtn.textContent = "Resume context";
    });
  } else if (audioCtx.state === "suspended") {
    audioCtx.resume().then(() => {
      susresBtn.textContent = "Suspend context";
    });
  }
};
```

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

| Specification |
| --- |
| Web Audio API # dom-audiocontext-suspend |

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

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

See also
--------

* Using the Web Audio API
* Web Audio API
AudioContext: sinkId property
=============================

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

 The **`sinkId`** read-only property of the
 `AudioContext` interface returns the sink ID of the current output audio device.

Value
-----

This property returns one of the following values, depending on how the sink ID was set:

An empty string

If a sink ID has not explicitly been set, the default system audio output device will be used, and `sinkId` will return an empty string.

A string

If the sink ID is set as a string value (using `setSinkId()`, or the `sinkId` `AudioContext()` constructor option), `sinkId` will return that same string value.

An `AudioSinkInfo` object

If the sink ID is set as an options object (using `setSinkId()`, or the `sinkId` `AudioContext()` constructor option), `sinkId` will return an `AudioSinkInfo` object reflecting the same values set in the initial options object.

Examples
--------

In our SetSinkId test example, we create an audio graph that generates a three-second burst of white noise via an `AudioBufferSourceNode`, which we also run through a `GainNode` to quiet things down a bit. We also provide the user with a dropdown menu to allow them to change the audio output device.

When the Play button is clicked, we assemble the audio graph and start it playing, and we also log information about the current device to the console based on the value of `sinkId`:

* An empty string means the default device is still being used.
* If the value is an object, the audio will not be playing on any device because we set an options object containing `type: 'none'`.
* Otherwise the value will be a sink ID string, so we log that.


```js
playBtn.addEventListener("click", () => {
  const source = audioCtx.createBufferSource();
  source.buffer = myArrayBuffer;
  source.connect(gain);
  gain.connect(audioCtx.destination);
  source.start();

  if (audioCtx.sinkId === "") {
    console.log("Audio playing on default device");
  } else if (
    typeof audioCtx.sinkId === "object" &&
    audioCtx.sinkId.type === "none"
  ) {
    console.log("Audio not playing on any device");
  } else {
    console.log(`Audio playing on device ${audioCtx.sinkId}`);
  }
});
```

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

| Specification |
| --- |
| Web Audio API # dom-audiocontext-sinkid |

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

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

See also
--------

* SetSinkId test example
* Change the destination output device in Web Audio
* `AudioContext.setSinkId()`
* `sinkchange`
AudioContext: baseLatency property
==================================

 The **`baseLatency`** read-only property of the
 `AudioContext` interface returns a double that represents the number of
 seconds of processing latency incurred by the `AudioContext` passing an audio
 buffer from the `AudioDestinationNode` — i.e. the end of the audio graph —
 into the host system's audio subsystem ready for playing.


**Note:** You can request a certain latency during
 construction time with the
 `latencyHint` option, but the browser may ignore the option.


Value
-----

A double representing the base latency in seconds.

Examples
--------


```js
// default latency ("interactive")
const audioCtx1 = new AudioContext();
console.log(audioCtx1.baseLatency); // 0.00

// higher latency ("playback")
const audioCtx2 = new AudioContext({ latencyHint: "playback" });
console.log(audioCtx2.baseLatency); // 0.15
```

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

| Specification |
| --- |
| Web Audio API # dom-audiocontext-baselatency |

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

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

See also
--------

* Using the Web Audio API
* Web Audio API
Text: splitText() method
========================

 The **`splitText()`** method of the `Text` interface
 breaks the `Text` node into two nodes at the specified offset,
 keeping both nodes in the tree as siblings.

 After the split, the current node contains all the content
 up to the specified offset point,
 and a newly created node of the same type contains the remaining text.
 The newly created node is returned to the caller.
 If the original node had a parent, the new node is inserted as the next sibling of the original node.
 If the offset is equal to the length of the original node,
 the newly created node has no data.

 Separated text nodes can be concatenated using the `Node.normalize()`
 method.

Syntax
------


```js
newNode = textNode.splitText(offset)
```

### Parameters

`offset`

The index immediately before which to break the text node.

### Return value

 Returns the newly created `Text` node that contains the text after the
 specified offset point.

### Exceptions

`IndexSizeError` `DOMException`

 Thrown if the specified offset is negative or is greater
 than the number of 16-bit units in the node's text.


`NoModificationAllowedError` `DOMException`

Thrown if the node is read-only.

Example
-------

 In this example, the text of a `<p>` is split into two text nodes, and a
 `<u>` is inserted between them.


```html
<p>foobar</p>
```



```js
const p = document.querySelector("p");

// Get contents of <p> as a text node
const foobar = p.firstChild;

// Split 'foobar' into two text nodes, 'foo' and 'bar',
// and save 'bar' as a const
const bar = foobar.splitText(3);

// Create a <u> element containing ' new content '
const u = document.createElement("u");
u.appendChild(document.createTextNode(" new content "));

// Add <u> before 'bar'
p.insertBefore(u, bar);

// The result is: <p>foo<u> new content </u>bar</p>
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-text-splittext① |

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

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

See also
--------

* The `Text` interface it belongs to.
* The opposite method: `Node.normalize`.
Text: assignedSlot property
===========================

 The read-only **`assignedSlot`** property of the `Text` interface
 returns the `HTMLSlotElement` object associated with the element.

Value
-----

 An `HTMLSlotElement`,
 or `null` if no `<slot>` element is associated with the text node.

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

| Specification |
| --- |
| DOM Standard # dom-slotable-assignedslot |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Text: Text() constructor
========================

 The **`Text()`** constructor returns a new `Text` object
 with the optional string given in parameter as its textual content.

Syntax
------


```js
new Text()
new Text(string)
```

### Parameters

* `string` Optional
### Return value

A new `Text` object with the content of the `string` parameter, or the empty string if no parameter was given.

Example
-------


```js
let text = new Text("Test");
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-text-text① |

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

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

See also
--------

* The DOM API
Text: wholeText property
========================

 The read-only **`wholeText`** property of the `Text` interface
 returns the full text of all `Text` nodes logically adjacent to the node.
 The text is concatenated in document order.
 This allows specifying any text node and obtaining all adjacent text as a single string.


**Note:** This is similar to call `Node.normalize()` followed by reading the text value,
 but without modifying the tree.


Value
-----

A string with the concatenated text.

Example
-------

Suppose you have the following simple paragraph within your webpage:


```html
<p>
  Through-hiking is great!
  <strong>No insipid election coverage!</strong> However,
  <a href="https://en.wikipedia.org/wiki/Absentee\_ballot">casting a ballot</a>
  is tricky.
</p>
```


You decide you don't like the middle sentence, so you remove it:


```js
const paragraph = document.querySelector("p"); // Reads the paragraph
paragraph.removeChild(para.childNodes[1]); // Delete the strong element
```


Now you end up with *"Through-hiking is great! However, casting a ballot is tricky."*, with two nodes before the hyperlink:

1. A `Text` containing the string `"Through-hiking is great!"`
2. A second `Text` node containing the string `" However, "`

To get those two nodes at once, you would call `para.childNodes[0].wholeText`:


```js
console.log(`'${paragraph.childNodes[0].wholeText}'`); // 'Through-hiking is great! However, '
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-text-wholetext① |

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

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

See also
--------

* The `Text` interface it belongs to.
ScreenDetailed: top property
============================

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

 The **`top`** read-only property of the
 `ScreenDetailed` interface is a number representing the y-coordinate (top edge) of the total screen area inside the OS virtual screen arrangement, relative to the multi-screen origin.

This is equal to the true top edge, ignoring any OS UI element drawn at the top of the screen. Windows cannot be placed in those areas; to get the top coordinate of the screen area that windows can be placed in, use `ScreenDetailed.availTop`.

**Note:** In Firefox, a non-standard implementation of the `top` property is available on the `Screen` interface. See the Non-standard example below for usage details, and see the `Screen` reference page for browser support information relating to the non-standard implementation.

Value
-----

A number.

Examples
--------

### Window Management API example


```js
// Available in browsers that support the Window Management API
const screenDetails = await window.getScreenDetails();

// Return the absolute top value of the first screen
const screen1Top = screenDetails.screens[0].top;
```

### Non-standard example


```js
// Available in Firefox
// Return the absolute top value of the current screen
const screenTop = window.screen.top;
```

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

| Specification |
| --- |
| Window Management # ref-for-dom-screendetailed-top |

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

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

See also
--------

* Window Management API
ScreenDetailed: devicePixelRatio property
=========================================

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

 The **`devicePixelRatio`** read-only property of the
 `ScreenDetailed` interface is a number representing the screen's device pixel ratio.

This is the same as the value returned by `Window.devicePixelRatio`, except that `Window.devicePixelRatio`:

* always returns the device pixel ratio for the current screen.
* also includes scaling of the window itself, i.e. page zoom (at least on some browser implementations).
Value
-----

A number.

Examples
--------


```js
const screenDetails = await window.getScreenDetails();

// Return the device pixel ratio of the first screen
const screen1DPR = screenDetails.screens[0].devicePixelRatio;
```

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

| Specification |
| --- |
| Window Management # ref-for-dom-screendetailed-devicepixelratio |

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

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

See also
--------

* Window Management API
ScreenDetailed: availLeft property
==================================

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

 The **`availLeft`** read-only property of the
 `ScreenDetailed` interface is a number representing the x-coordinate (left-hand edge) of the available screen area inside the OS virtual screen arrangement, relative to the multi-screen origin.

This is equal to the `ScreenDetailed.left` property, plus the width of any OS UI element drawn on the left of the screen. Windows cannot be placed in those areas, so `availLeft` is useful for giving you the left boundary of the actual area available to open or place windows.

**Note:** A non-standard implementation of the `availLeft` property is available on the `Screen` interface in all browsers. See the Non-standard example below for usage details, and see the `Screen` reference page for browser support information relating to the non-standard implementation.

Value
-----

A number.

Examples
--------

### Window Management API example


```js
// Available in browsers that support the Window Management API
const screenDetails = await window.getScreenDetails();

// Return the availLeft value of the first screen
const screen1AvailLeft = screenDetails.screens[0].availLeft;
```

### Non-standard example


```js
// Available in all browsers
// Return the availLeft value of the current screen
const screenAvailLeft = window.screen.availLeft;
```

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

| Specification |
| --- |
| Window Management # ref-for-dom-screendetailed-availleft |

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

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

See also
--------

* Window Management API