Created
October 26, 2016 17:34
-
-
Save saschas/2494d051fa9b6e75d431c18c08371c4b to your computer and use it in GitHub Desktop.
This file contains 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
function AudioBufferLoader(context) { | |
this.context = context; | |
this.loadCount = 0; | |
this.bufferList = {}; | |
} | |
AudioBufferLoader.prototype.loadBuffer = function(name,url, cb) { | |
if(name in this.bufferList){ | |
cb(this.bufferList[name]); | |
}else{ | |
// Load buffer asynchronously | |
var request = new XMLHttpRequest(); | |
request.open("GET", url, true); | |
request.responseType = "arraybuffer"; | |
var that = this; | |
request.onload = function() { | |
// Asynchronously decode the audio file data in request.response | |
that.context.decodeAudioData( | |
request.response, | |
function(buffer) { | |
if (!buffer) { | |
console.log('error decoding file data: ' + url); | |
return; | |
} | |
that.bufferList[name] = buffer; | |
cb(that.bufferList[name]); | |
}, | |
function(error) { | |
console.error('decodeAudioData error', error); | |
}); | |
}//onload | |
request.onerror = function() { | |
console.log('BufferLoader: XHR error'); | |
}//onerror | |
request.send(); | |
} | |
} |
This file contains 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
try { | |
// Fix up for prefixing | |
window.AudioContext = window.AudioContext||window.webkitAudioContext; | |
context = new AudioContext(); | |
var bufferLoader = new AudioBufferLoader( context); | |
//bufferLoader.load(); | |
} | |
catch(e) { | |
console.log('Web Audio API is not supported in this browser'); | |
} | |
//load single Buffer | |
audioData.bufferLoader.loadBuffer(name, url,function(buffer) {}); | |
function createSource(buffer) { | |
var source = context.createBufferSource(); | |
source.buffer = buffer; | |
// Connect gain to destination. | |
source.connect(context.destination); | |
return { | |
source: source, | |
}; | |
} | |
function playSound(source,buffer,loop) { | |
source = createSource(buffer); | |
source.source.loop = loop; | |
source.playing = true; | |
source.source.start ? source.source.start() : source.source.noteOn(0); | |
return source; | |
} | |
//play | |
playSound(source,buffer,loop); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment