Last active
August 29, 2015 14:02
-
-
Save notthetup/ecca5b48a7fb47473ab5 to your computer and use it in GitHub Desktop.
A function to get Audio From URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * 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