Loading Sound using Preloadjs fails, but does not call error event

317 Views Asked by At

I use the following code to load and play a sound using the CreateJS library. This works fine, but the problem is that neither callback is called when a file could not be loaded, for example the sound does not exist on the server (this is a valid use case).

How can I change this code so that whenever an error occured while loading the file, it calls my error callback function?

// define example play sound function
function playMySound(loadFileName, callbackDone, callbackError){

    var queue = new createjs.LoadQueue(false);      
    queue.installPlugin(createjs.Sound);  

    queue.on("fileload", function(evt){
        var instance = createjs.Sound.play(loadFileName, createjs.Sound.INTERRUPT_EARLY, 0, 0, false);

        instance.addEventListener("complete", function(){
            createjs.Sound.removeSound(loadFileName);  

            // call done callback
            if(callbackDone){
                callbackDone();
            }

        }); 
    });
    queue.on("error", function(evt){
        console.error("Sound could not be loaded");

        // call error callback
        if (callbackError){
            callbackError();
        }
    });

    queue.loadFile(loadFileName, false);
    queue.load();

}



//define callback functions
var callbackDone = function(){console.log("Done playing..")};
var callbackError = function(){return alert('This sound does not exist');};

// try to play sound
playMySound("/path/to/my/sound.mp3",callbackDone,callbackError);
0

There are 0 best solutions below