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.
html>
body>
/body>
script>
var soundRequest = new [XMLHttpRequest](/blog/532/)();
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 webkitAudio[Context](/blog/498/)();
var mainNode = context.createGainNode(0);
mainNode.connect(context.destination);
var clip = context.createBufferSource();
context.decodeAudio[Data](/blog/824/)(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](/blog/488/) Audio API is not supported in this browser');
}
};
soundRequest.send();
};
setup();
/script>
/html>