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 experimental <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
It 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
It inherits all methods from AudioNode.
Remarks
Native routing
- On native, the underlying file source is disconnected from the destination when this node is created so audio is not processed twice.
- Use the same
AudioTagHandlefor transport controls (play,pause,seekToTime,volume).