MediaElementAudioSourceNode
The MediaElementAudioSourceNode is an AudioNode that routes media playback into the audio graph.
On the web it mirrors AudioContext.createMediaElementSource() and accepts an HTMLMediaElement.
On the native it wraps a file-backed source created by the <Audio> tag.
Constructor
constructor(context: BaseAudioContext, options: MediaElementAudioSourceOptions)
MediaElementAudioSourceOptions
| Parameter | Type | Default | |
|---|---|---|---|
mediaElement | HTMLMediaElement (web) | AudioTagHandle (native) | — | Media element whose audio is routed into the graph. On native, wait for onLoad before constructing this node. |
Or by using AudioContext factory method:
AudioContext.createMediaElementSource()
Errors
| Error type | Description |
|---|---|
InvalidStateError | Creating second node from the same media element. |
Example
import React, { useRef } from 'react';
import {
AudioContext,
GainNode,
Audio,
AudioTagHandle,
} from 'react-native-audio-api';
function WebExample() {
const audioContextRef = useRef<AudioContext | null>(null);
if (!audioContextRef.current) {
audioContextRef.current = new AudioContext();
}
const audioElement = document.querySelector('audio')!;
const sourceNode =
audioContextRef.current.createMediaElementSource(audioElement);
sourceNode.connect(audioContextRef.current.destination);
}
function NativeExample() {
const audioContextRef = useRef<AudioContext | null>(null);
const audioRef = useRef<AudioTagHandle>(null);
if (!audioContextRef.current) {
audioContextRef.current = new AudioContext();
}
const routeThroughGraph = () => {
if (!audioRef.current || !audioContextRef.current) {
return;
}
const mediaElementSource = audioContextRef.current.createMediaElementSource(
audioRef.current
);
const gain = audioContextRef.current.createGain();
mediaElementSource.connect(gain);
gain.connect(audioContextRef.current.destination);
audioRef.current.play();
};
return (
<Audio
ref={audioRef}
source="https://example.com/audio.mp3"
context={audioContextRef.current}
onLoad={routeThroughGraph}
/>
);
}
Properties
Inherits all properties from AudioNode.
AudioNodeproperties| Name | Type | Default value | Description |
|---|---|---|---|
mediaElement Read only | HTMLMediaElement | AudioTagHandle | — | The media element routed into the audio graph. |
Methods
Inherits all methods from AudioNode.
AudioNodemethodsMediaElementAudioSourceNode does not define any additional methods.
Remarks
Native routing
- From the moment this node is created, the
<Audio>is heard only through it, including after it reaches its end and is played again. While the node is not connected to anything, the tag keeps playing silently, as in the browser. - To hear the
<Audio>unprocessed again, connect the node to the destination: a tag cannot be given back or routed through a second node. - Use the same
AudioTagHandlefor transport controls (play,pause,seekToTime,volume).