AudioContext: createMediaElementSource() 方法

Baseline 已广泛支持

此特性已得到良好支持,可在多种设备和浏览器版本上使用。自 2021 年 4 月起,所有浏览器均已支持此特性。

AudioContext 接口的 createMediaElementSource() 方法用于根据一个现有的 HTML <audio><video> 元素创建一个新的 MediaElementAudioSourceNode 对象,该对象的音频可以被播放和操作。

有关媒体元素音频源节点的更多详细信息,请参阅 MediaElementAudioSourceNode 参考页。

语法

js
createMediaElementSource(myMediaElement)

参数

myMediaElement

一个 HTMLMediaElement 对象,您想将其馈送到音频处理图中进行操作。

返回值

一个 MediaElementAudioSourceNode

示例

这个简单的示例使用 createMediaElementSource() 从一个 <audio> 元素创建了一个源,然后将音频通过一个 GainNode 传递,最后将其馈送到 AudioDestinationNode 进行播放。当鼠标指针移动时,将调用 updatePage() 函数,该函数将当前增益计算为鼠标 Y 坐标除以整个窗口高度的比率。因此,您可以通过上下移动鼠标指针来增加和减小正在播放的音乐的音量。

注意:您也可以 查看此示例的实时运行,或 查看源代码

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);

注意:调用 createMediaElementSource() 的结果是,来自 HTMLMediaElement 的音频播放将被重新路由到 AudioContext 的处理图中。因此,仍然可以通过媒体元素 API 和播放器控件来播放/暂停媒体。

规范

规范
Web Audio API
# dom-audiocontext-createmediaelementsource

浏览器兼容性

另见