SoundJS - registering 4 sounds in an audiosprite

368 Views Asked by At

I'm loading a SoundJS 1.0 audiosprite with preloadJS 1.0. The audiosprite is split into 4 sounds which I'm calling a,b,c and d. (Elsewhere in the code it randomizes which of the 4 sounds to play.)

Here's the basic loading and declaration code:

 var queue = new createjs.LoadQueue();
 createjs.Sound.alternateExtensions = ["mp3"];
 queue.addEventListener("complete",handleComplete);

 //load audiosprite and define start/duration times with variables.
 queue.loadFile({src:path,data:{
     audioSprite:[
     {id:sound+"a", startTime:aStart, duration: aDur},
     {id:sound+"b", startTime:bStart, duration: bDur},
     {id:sound+"c", startTime:cStart, duration: cDur},
     {id:sound+"d", startTime:dStart, duration: dDur},
     ]
     }});

 //register the 4 audioSprite sounds as individual sound instances
    myAudio[sound+"a"] = createjs.Sound.createInstance(sound+"a");
    myAudio[sound+"b"] = createjs.Sound.createInstance(sound+"b");
    myAudio[sound+"c"] = createjs.Sound.createInstance(sound+"c");
    myAudio[sound+"d"] = createjs.Sound.createInstance(sound+"d");

When I load the sound I get: Uncaught TypeError: Cannot read property '1' of null

If I comment out the last 3 lines and just create 1 instance (eg. sound+"a"), the sound loads and I get no error, but obviously I only get 1 of the 4 parts.

I feel like the problem is it doesn't like me calling createInstance back to back like this. What is the correct way to do this?

1

There are 1 best solutions below

3
opd On

You need to use loadManifest for multiple files; loadFile only loads a single file.

 queue.loadManifest({src:path,data:{
 audioSprite:[
 {id:sound+"a", startTime:aStart, duration: aDur},
 {id:sound+"b", startTime:bStart, duration: bDur},
 {id:sound+"c", startTime:cStart, duration: cDur},
 {id:sound+"d", startTime:dStart, duration: dDur},
 ]
 }});

Edit - the handlePreloadComplete function from line 286 looks a bit suspect and may be a bug https://createjs.com/docs/soundjs/files/soundjs_AbstractPlugin.js.html

p._handlePreloadComplete = function (event) {
    var src = event.target.getItem().src;
    this._audioSources[src] = event.result;
    for (var i = 0, l = this._soundInstances[src].length; i < l; i++) {
        var item = this._soundInstances[src][i];
        item.playbackResource = this._audioSources[src];
        // ToDo consider adding play call here if playstate == playfailed
        this._soundInstances[src] = null;
    }
};

Iterating over the length of this._soundInstances[src], but then setting it to null on the first iteration will give the error you mention.

Perhaps it should be

this._soundInstances[src][i] = null;