Skip to content

Instantly share code, notes, and snippets.

@notthetup
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save notthetup/ecca5b48a7fb47473ab5 to your computer and use it in GitHub Desktop.

Select an option

Save notthetup/ecca5b48a7fb47473ab5 to your computer and use it in GitHub Desktop.
A function to get Audio From URL
/*
* Downloads a sound file using XHR and decodes it using WebAudio
*
* @method GetAudioFromURL
* @param {String} URL URL of the audio file to be downloaded.
* @param {Function} onLoadCallback Callback for when the decoded AudioBuffer is ready. Callback returns an {Error} (if any) and an {AudioBuffer}
* @param {Function} onProgressCallback Callback for progress event from the XHR download.
* @param {AudioContext} [AudioContext] Optional AudioContext to be used for decoding.
*
*/
function GetAudioFromURL(URL, onLoadCallback, onProgressCallback, audioContext){
if (!audioContext){
window.AudioContext = window.AudioContext || window.webkitAudioContext
audioContext = new AudioContext();
}
var request = new XMLHttpRequest();
request.open('GET', URL, true);
request.responseType = 'arraybuffer';
request.onload = function () {
audioContext.decodeAudioData(request.response, function(buffer){
if (typeof onLoadCallback === 'function')
onLoadCallback(null, buffer);
},function (){
if (typeof onLoadCallback === 'function')
onLoadCallback(new Error("Decoding Error"), null);
});
};
request.onerror = function(){
if (typeof onLoadCallback === 'function')
onLoadCallback(new Error("Loading Error"), null);
}
request.onprogress = function(event){
if (typeof onProgressCallback === 'function'){
onProgressCallback(event);
}
}
request.send();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment