MDN’s new design is in Beta! A sneak peek: https://blog.mozilla.org/opendesign/mdns-new-design-beta/

AudioContext.createMediaElementSource()

AudioContext 接口的 createMediaElementSource() 方法用于创建一个新的 MediaElementAudioSourceNode 对象,输入某个存在的 HTML <audio> or <video> 元素, 对应的音频即可被播放或者修改.

为寻求更多关于媒体元素音频源节点的具体信息,请查阅 MediaElementAudioSourceNode 参考页.

语法

var audioCtx = new AudioContext();
var source = audioCtx.createMediaElementSource(myMediaElement);

参数

myMediaElement
某个被期待被录入音频处理图修改的 HTMLMediaElement 对象.

返回值

一个 MediaElementAudioSourceNode 对象.

示例

该示例由 <audio> 元素,通过使用 createMediaElementSource() 方法,创建了一个音源,将其通过 GainNode 节点,输出到AudioDestinationNode 节点以播放.当鼠标指针移动时, updatePage() 函数被调用,该函数计算当前鼠标Y坐标与页面高度的比值, 改变 GainNode 节点的值以调整音量.您就可以通过鼠标上下移动而改变音乐的音量了.

Note: 您也可以 浏览该示例的在线演示, 或者 浏览源代码.

var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var myAudio = document.querySelector('audio');
var pre = document.querySelector('pre');
var myScript = document.querySelector('script');

pre.innerHTML = myScript.innerHTML;

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

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

// Create variables to store mouse pointer Y coordinate
// and HEIGHT of screen
var CurY;
var HEIGHT = window.innerHeight;

// Get new mouse pointer coordinates when mouse is moved
// then set new gain value

document.onmousemove = updatePage;

function updatePage(e) {
    CurY = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);

    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: 作为调用 createMediaElementSource() 的结果,HTMLMediaElement 的播放将会由AudioContext的音频处理图接管.所以对媒体进行播放/暂停等操作仍可通过media API与播放器面板来进行.

规范

Specification Status Comment
Web Audio API
createMediaElementSource()
Working Draft  

浏览器兼容性

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 10.0webkit (Yes) 25.0 (25.0)  未实现 15.0webkit
22

6.0webkit

- buggy! not working -

Feature Android Edge Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support ? (Yes) 26.0 1.2 ? ?

?

- buggy! not working -

33.0

相关链接

文档标签和贡献者

 此页面的贡献者: Corps
 最后编辑者: Corps,