Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - Stop HTML5 audio from looping when iOS Safari is closed

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...