The decodeAudioData()
method of the BaseAudioContext
Interface is used to asynchronously decode audio file data contained in an ArrayBuffer
. In this case the ArrayBuffer
is loaded from XMLHttpRequest
and FileReader
. The decoded AudioBuffer
is resampled to the AudioContext
's sampling rate, then passed to a callback or promise.
This is the preferred method of creating an audio source for Web Audio API from an audio track. This method only works on complete file data, not fragments of audio file data.
decodeAudioData(arrayBuffer, successCallback)
decodeAudioData(arrayBuffer, successCallback, errorCallback)
decodeAudioData(arrayBuffer)
Void, or a Promise
object that fulfills with the decodedData.
In this section we will first cover the older callback-based system and then the newer promise-based syntax.
In this example, the getData()
function uses XHR to load an audio track, setting the responseType
of the request to arraybuffer
so that it returns an array buffer as its response
that we then store in the audioData
variable . We then pass this buffer into a decodeAudioData()
function; the success callback takes the successfully decoded PCM data, puts it into an AudioBufferSourceNode
created using AudioContext.createBufferSource()
, connects the source to the AudioContext.destination
and sets it to loop.
The buttons in the example run getData()
to load the track and start it playing, and stop it playing, respectively. When the stop()
method is called on the source, the source is cleared out.
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var source;
var pre = document.querySelector('pre');
var myScript = document.querySelector('script');
var play = document.querySelector('.play');
var stop = document.querySelector('.stop');
function getData() {
source = audioCtx.createBufferSource();
var request = new XMLHttpRequest();
request.open('GET', 'viper.ogg', true);
request.responseType = 'arraybuffer';
request.onload = function() {
var audioData = request.response;
audioCtx.decodeAudioData(audioData, function(buffer) {
source.buffer = buffer;
source.connect(audioCtx.destination);
source.loop = true;
},
function(e){ console.log("Error with decoding audio data" + e.err); });
}
request.send();
}
play.onclick = function() {
getData();
source.start(0);
play.setAttribute('disabled', 'disabled');
}
stop.onclick = function() {
source.stop(0);
play.removeAttribute('disabled');
}
pre.innerHTML = myScript.innerHTML;
ctx.decodeAudioData(audioData).then(function(decodedData) {
});