Stop HTML5 audio from looping when iOS Safari is closed

后端 未结 1 1224
北恋
北恋 2020-12-11 13:02

Okay, so I\'ve got something as simple as this:

相关标签:
1条回答
  • 2020-12-11 13:31

    Managed to find a solution:

    Make use of a loop, to check if the user is on the webpage. Store the time.

    var lastSeen;
    var loop = function (){
        lastSeen = Date.now();
        setTimeout(loop, 50);
    };
    loop();
    
    var music = document.getElementById('music');
    music.addEventListener('timeupdate', function (){
        if(Date.now() - lastSeen > 100){
            this.pause();
        }
    }, false);
    

    That's roughly what my file looks like. Since the timeupdate event fires on an audio element continually if it's playing, I only have to check when my loop was last called. If it was called more than 100ms ago, I pause the music. Worked like a charm on the iPad I tested on.

    0 讨论(0)
提交回复
热议问题