Search code examples
javascripthtmlgoogle-chromeaudiopreload

Preload multiple (798) audio files in Chrome


I making a game and I want to load 798 sound files, but there is a problem only in Chrome, Firefox fine. Sample code: https://jsfiddle.net/76zb42ag/, see the console (press F12).

Sometimes script loads only 100, 500, 700 files, sometimes is fine. If i reduce the number of files to ex. 300 is ok (always). How can I solve this problem? I need a callback or any ideas? The game will be offline (node webkit).

Javascript code :

var total = 0;
// sample file to download: http://www.sample-videos.com/audio/mp3/crowd-cheering.mp3
// sounds.length = 798 files 
var sounds = [

    (...limit character, see https://jsfiddle.net/76zb42ag/...)
];

for (var i in sounds) {
    load(sounds[i]);
}

function load(file) {
    var snd = new Audio();
    snd.addEventListener('canplaythrough', loadedAudio, false);
    snd.src = file;
}


function loadedAudio() {
    total++;
    console.log(total);
    if (total == sounds.length){
        console.log("COMPLETE");
    }
}

Solution

  • This isn't really a code problem. It's a general architecture problem.

    Depending not only on the number, but also the size of the samples, it's going to be unlikely you can get them all loaded at once. Even if you can, it'll run very poorly because of the high memory use and likely crash the tab after a certain amount of time.

    Since it's offline, I would say you could even get away with not pre-loading them at all, since the read speed is going to be nearly instantaneous.

    If you find that isn't suitable, or you may need like 5 at once and it might be too slow, I'd say you'll need to architect your game in a way that you can determine which sounds you'll need for a certain game state, and just load those (and remove references to ones you don't need so they can be garbage collected).

    This is exactly what all games do when they show you a loading screen, and for the same reasons.

    If you want to avoid "loading screens", you can get clever by working out a way to know what is coming up and load it just ahead of time.