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.
createMediaElementSource(myMediaElement)
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.
const audioCtx = new AudioContext();
const myAudio = document.querySelector("audio");
const source = audioCtx.createMediaElementSource(myAudio);
const gainNode = audioCtx.createGain();
let curY;
const HEIGHT = window.innerHeight;
document.onmousemove = updatePage;
function updatePage(e) {
curY = e.pageY;
gainNode.gain.value = curY / HEIGHT;
}
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.