Loading Sound

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.


        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);

                    var clip = context.createBufferSource();

                    context.decodeAudioData(soundRequest.response, function (buffer) {
                        clip.buffer = buffer;
                        clip.gain.value = 1.0;
                        clip.loop = true;
                    }, function (data) {});
                catch(e) {
                    console.warn('Web Audio API is not supported in this browser');



Edit tutorial

Comment on This Data Unit