Skip to content

Instantly share code, notes, and snippets.

@the-frey
Last active December 18, 2015 05:09
Show Gist options
  • Save the-frey/5730174 to your computer and use it in GitHub Desktop.
Save the-frey/5730174 to your computer and use it in GitHub Desktop.
Abstraction of XHR written as part of Udacity's HTML5 Game course. Kinda neat.
function xhrGet(reqUri, callback, type) {
var caller = this.caller;
var xhr = new XMLHttpRequest();
xhr.open("GET", reqUri, true);
if(type){
xhr.responseType = type;
}
xhr.onload = function(){
if(callback){
try {
callback(xhr);
} catch(e) {
throw "xhrGet failed: \n" + reqUri + "\n Exception: " + e + "\n Response text: " + xhr.responseText + "\n Caller: " + caller;
}
}
};
xhr.send();
}
parseJSON = function (xhr) {
var parsedJSON = JSON.parse(xhr.responseText);
var x = parsedJSON['frames']['chaingun_impact.png']['spriteSourceSize']['x'];
console.log(x);
return x;
};
playSound = function (xhr) {
try {
var context = new webkitAudioContext();
var mainNode = context.createGainNode(0);
mainNode.connect(context.destination);
var clip = context.createBufferSource();
context.decodeAudioData(xhr.response, function (buffer) {
clip.buffer = buffer;
clip.gain.value = 1.0;
clip.connect(mainNode);
clip.loop = true;
clip.noteOn(0);
}, function (data) {});
}
catch(e) {
console.warn('Web Audio API is not supported in this browser');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment