我们一直在 Firefox 中实现 Web Audio API,目前已在 Firefox Nightly 和 Firefox Aurora 中实现了对该 API 的基本支持。Web Audio 提供了许多很酷的功能,可用于创建音乐应用程序、游戏以及基本上任何需要高级音频处理的应用程序。
功能
以下是一些功能示例
- 在音频播放期间安排事件在精确的时间发生
- 各种类型的音频滤波器,用于创建回声、降噪等效果。
- 声音合成,用于创建电子音乐
- 3D 定位音频,用于模拟游戏场景中声源移动等效果
- 与 WebRTC 集成,以将效果应用于来自外部输入(WebRTC 通话、插入设备的吉他等)的声音,或应用于传输到 WebRTC 通话中另一方的音频
- 分析音频数据以创建声音可视化器等。
代码示例
这是一个使用 Web Audio 可以构建的简单示例。假设您正在开发一款游戏,并且希望在玩家点击游戏画布时播放枪声。为了确保您不受网络延迟、音频解码器延迟等因素的影响,您可以使用 Web Audio 将音频预加载到缓冲区中,作为游戏加载过程的一部分,并在收到点击事件时精确地安排播放。
为了创建更清晰的音效,我们还可以持续播放声音,直到鼠标按下,并在释放鼠标时创建淡出效果。以下代码示例展示了如何执行此操作。
// Load the sound file from the network
var decodedBuffer;
var ctx = new AudioContext();
var xhr = new XMLHttpRequest();
xhr.open("GET", "gunshot.ogg", true);
xhr.responseType = "arraybuffer";
xhr.send();
xhr.onload = function() {
// At this point, xhr.response contains the encoded data for gunshot.ogg,
// so let's decode it into an AudioBuffer first.
ctx.decodeAudioData(xhr.response, function onDecodeSuccess(buffer) {
decodedBuffer = buffer;
}, function onDecodeFailure() { alert('decode error!'); });
};
// Set up a mousedown/mouseup handler on your game canvas
canvas.addEventListener("mousedown", function onMouseDown() {
var src = ctx.createBufferSource();
src.buffer = decodedBuffer; // play back the decoded buffer
src.loop = true; // set the sound to loop while the mouse is down
var gain = ctx.createGain(); // create a gain node in order to create the fade-out effect when the mouse is released
src.connect(gain);
gain.connect(ctx.destination);
canvas.src = src; // save a reference to our nodes to use it later
canvas.gain = gain;
src.start(0); // start playback immediately
}, false);
canvas.addEventListener("mouseup", function onMouseUp() {
var src = canvas.src, gain = canvas.gain;
src.stop(ctx.currentTime + 0.2); // set up playback to stop in 200ms
gain.gain.setValueAtTime(1.0, ctx.currentTime);
gain.gain.linearRampToValueAtTime(0.001, ctx.currentTime + 0.2); // set up the sound to fade out within 200ms
}, false);
首个 WebAudio 实现和 WebKit
Web Audio API 最初是在 Google Chrome 中使用 webkitAudioContext
前缀实现的。我们一直在 W3C 音频工作组讨论该 API,并一直在尝试解决 API 早期版本中的一些问题。在某些情况下,这意味着我们需要破坏针对 webkitAudioContext
的代码的后向兼容性。
有一份 指南介绍如何将这些应用程序移植到标准 API。还有一个可用的 webkitAudioContext 猴子补丁,它可以自动处理其中的一些更改,这有助于使一些针对 webkitAudioContext
的代码在标准 API 中工作。
Firefox 中的实现
在 Firefox 中,我们实现了标准 API。如果您是一位对在 Web 上创建高级音频应用程序感兴趣的 Web 开发人员,审查 将 webkitAudioContext 代码移植到基于标准的 AudioContext 将非常有帮助,以便了解通过标准化过程对 API 进行的所有不向后兼容的更改。
我们目前希望在 Firefox 24 桌面版和 Android 版中发布 Web Audio 支持,除非发生一些意外情况导致我们延迟发布,但您现在可以在 Nightly 和 Aurora 上使用 API 的大部分功能。
还有一些缺失的部分,包括 MediaStreamAudioSourceNode
、MediaElementAudioSourceNode
、OscillatorNode
和 PannerNode
的 HRTF 泛音。我们将在接下来的几周内在 Nightly 和 Firefox Aurora 上添加对 API 剩余部分的支持。
关于 Ehsan Akhgari
Ehsan 从事 Gecko 中的各种功能开发。
关于 Robert Nyman [荣誉编辑]
技术布道师和 Mozilla Hacks 编辑。发表关于 HTML5、JavaScript 和开放 Web 的演讲和博客文章。Robert 是 HTML5 和开放 Web 的坚定支持者,自 1999 年以来一直从事 Web 前端开发工作,在瑞典和纽约市都有工作经历。他还在 http://robertnyman.com 上定期发表博客文章,并且热爱旅行和结识新朋友。
16 条评论