web 音频 API 允许 Web 开发者使用 JavaScript 动态的加载 / 解码音频文件. 如果你经常开发一些 Web 游戏, 这些 API 你可能会经常用到. 下面是对 Web 音频 API 的简单介绍, 你可以使用这个 API 在 Web 前端替换改变音频的使用.
下面看一看使用 Web 音频 API 的代码例子:
- // Create an AudioContext instance for this sound
- var audioContext = new (Windows.AudioContext || Windows.webkitAudioContext)();
- // Create a buffer for the incoming sound content
- var source = audioContext.createBufferSource();
- // Create the XHR which will grab the audio contents
- var request = new XMLHttpRequest();
- // Set the audio file src here
- request.open('GET', 'sound-effect.mp3', true);
- // Setting the responseType to arraybuffer sets up the audio decoding
- request.responseType = 'arraybuffer';
- request.onload = function() {
- // Decode the audio once the require is complete
- audioContext.decodeAudioData(request.response, function(buffer) {
- source.buffer = buffer;
- // Connect the audio to source (multiple audio buffers can be connected!)
- source.connect(audioContext.destination);
- // Simple setting for the buffer
- source.loop = true;
- // Play the sound!
- source.start(0);
- }, function(e) {
- console.log('Audio error!', e);
- });
- }
- // Send the request which kicks off
- request.send();
上面的代码中我加入了注释, 尽量的把代码的作用描述清楚. 上面的代码只是一个简单的例子, 这个 API 实际上有更多的用法可用.
对于 Web 音频 API 我不是专家, 我只是非常兴奋, 看到使用 JavaScript 能实现这些神奇的功能. 使用它还可以用来滤音, 剪辑, 等等. 下面提供了一些关于 Web 音频 API 的资料, 从中你可以学到更多的知识:
- Web Audio API
- Using the Web Audio API
- Getting Started with Web Audio API
你使用 Web 音频 API 开发过什么精彩的应用吗? 分享给我们!
来源: http://www.webhek.com/post/web-audio-api.html