Stop HTML5 audio from looping when iOS Safari is c

2019-01-20 06:26发布

问题:

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

<audio autoplay='autoplay' loop='loop' id='audio' controls>
  <source src='http://www.w3schools.com/html/horse.ogg'/>
  <source src='http://www.w3schools.com/html/horse.mp3'/>
</audio>

Now, when I play the audio on an iOS device, it loops fine and everything, however, when I close the browser window, or switch tabs, it just keeps on looping and the only way to pause it is if I shut the browser tab. I tried removing the loop='loop' and replaying it onended with JavaScript, and that works, but with audio that is about 1.5 mins long, it can still be pretty annoying. but that didn't work either because the ended event fires even when the browser isn't open.

Demo in which the sound is the first one I could find online, but note that my actual sound is pretty long, so I do need to pause it when the browser window is closed.

I've tried pausing it onblur, onunload and onbeforeunload to no avail. Is there a way to stop the audio from playing in the background?

回答1:

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.