WEB音频API

WEB音频API允许WEB开发者使用JavaScript动态的加载/解码音频文件。如果你经常开发一些WEB游戏,这些API你可能会经常用到。下面是对WEB音频API的简单介绍,你可以使用这个API在WEB前端替换改变音频的使用。

下面看一看使用WEB音频API的代码例子:

// Create an AudioContext instance for this sound
var audioContext = new (window.AudioContext || window.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音频API开发过什么精彩的应用吗?分享给我们!

阅读余下内容
 

《“WEB音频API”》 有 2 条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注


京ICP备12002735号