Proper onload for <audio>

萝らか妹 提交于 2019-12-01 19:34:49

You can use the loadeddata-MediaEvent. For example you can put all of your audio files in an Array and do something like:

var files = ['a.mp3', 'b.mp3'];

$.each(files, function() {
    $(new Audio())
        .on('loadeddata', function() {
            var i = files.indexOf(this);
            files.splice(i, 1);
            if (!files.length) {
                alert('Preloading done!');
            }
        })
        .attr('src', this);
});

EDIT: this would a little more modern approach as of 2016:

var files = ['a.mp3','b.mp3'];

Promise
    .all(files.map(function(file) {
        return new Promise(function(resolve) {
            var tmp = new Audio();
            tmp.src = file;
            tmp.addEventListener('loadeddata', resolve);
        });
    })).then(function() {
        alert('Preloading done!');
    });

I did a small PONG-game with WebGL and some audio-tags for the sounds. I borrowed the audio-implementation from Opera's Emberwind HTML5 implementation: https://github.com/operasoftware/Emberwind/blob/master/src/Audio.js

Their solution worked fine for me (Chrome, Opera and Firefox). Maybe it could be of interest to you? They have some code that will try to find a playable format from line 22 and below.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!