Proper onload for <audio>

前端 未结 2 688
暗喜
暗喜 2021-01-19 10:02

I\'ve been looking around and I\'m starting to worry that this isn\'t possible.
Is there any way to make a standard tag with fallbacks...

相关标签:
2条回答
  • 2021-01-19 10:56

    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.

    0 讨论(0)
  • 2021-01-19 11:09

    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!');
        });
    
    0 讨论(0)
提交回复
热议问题