audiojquery-animatecreatejssoundjs

SoundJS - assigning sounds to variables


I am loading several mp3 files using loadManifest, but I am a bit confused by how I'd assign the loaded sounds to variables. Can I use createInstance here?

My code currently looks like this:

var myRoot = this;

var queue = new createjs.LoadQueue();
queue.addEventListener("fileload", handleFileLoad);
queue.addEventListener("complete", handleComplete);

queue.loadManifest([{ src: "media/file1.mp3", id: "sound1" },
                    { src: "media/file2.mp3", id: "sound2" },
                    { src: "media/file3.mp3", id: "sound3" }]);

function handleFileLoad(event) {    
    // assign each sound to unique variable
    myRoot.sound1 = createjs.Sound.createInstance("sound1");
    myRoot.sound2 = createjs.Sound.createInstance("sound2");
    myRoot.sound3 = createjs.Sound.createInstance("sound3");
}

function handleComplete(event) {
    // start playing sound1
    myRoot.sound1.play();
}

How can I create an instance of a sound using it's ID and assign it to a variable that I can easily access later? Do I need to register sounds before I am able to do that?

Thank you!


Solution

  • the following line was missing, and is all that was required for that code to work:

    queue.installPlugin(createjs.Sound); 
    

    That, and it's better to move variable assignments out to handleComplete function

    The complete working code looks like this:

    var myRoot = this;
    
    var queue = new createjs.LoadQueue();
    queue.installPlugin(createjs.Sound); 
    queue.addEventListener("complete", handleComplete);
    
    queue.loadManifest([{ src: "media/file1.mp3", id: "sound1" },
                        { src: "media/file2.mp3", id: "sound2" },
                        { src: "media/file3.mp3", id: "sound3" }]);
    
    function handleComplete(event) {
        // assign each sound to unique variable
        myRoot.sound1 = createjs.Sound.createInstance("sound1");
        myRoot.sound2 = createjs.Sound.createInstance("sound2");
        myRoot.sound3 = createjs.Sound.createInstance("sound3");
        // start playing sound1
        myRoot.sound1.play();
    }