created on Feb. 7, 2013, 9:23 p.m. by Hevok & updated on Feb. 7, 2013, 9:23 p.m. by Hevok
To load a sound file the responseType
of the request need to be set as arraybuffer
which will specify that it is binary information rather than text that then can be decoded if necessary. Doing this is necessary to work with any kind of binary data, like sound files, rather than text data.
The following code shows how to create a new XMLHttpRequest that GETs a sound file. The request's onload function will play the sound if loaded.
.. sourcecode:: js
<html>
<body>
</body>
<script>
var soundRequest = new XMLHttpRequest();
var setup = function() {
soundRequest.open("GET", '/media/js/standalone/libs/gamedev_assets/bg_menu.ogg', true);
soundRequest.responseType = 'arraybuffer';
soundRequest.onload = function () {
try {
var context = new webkitAudioContext();
var mainNode = context.createGainNode(0);
mainNode.connect(context.destination);
var clip = context.createBufferSource();
context.decodeAudioData(soundRequest.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');
}
};
soundRequest.send();
};
setup();
</script>
</html>
Comment on This Data Unit