问题
I have a web app that plays an HTML5 Audio stream of a radio station. I'm using jQuery to play/pause the audio and toggle the play/pause button like so:
var playerStream = document.getElementById('player-stream');
$('section.player').hammer().on('tap','button.toggle-stream', function(event){
if (playerStream.paused) {
playerStream.play();
$('button.toggle-stream').attr('data-icon','s');
}
else {
playerStream.pause();
$('button.toggle-stream').attr('data-icon','p');
}
});
This all works great. However, on devices like iPhone and iPad you can control the audio playing from outside of the web page (for example double-clicking on the home screen and clicking play/pause). Let's say the audio is playing and from outside the app I decide to pause the stream. When I return to the actual web app the 'pause' button still shows and effectively does nothing until you tap it twice to resume the stream. What should really happen is the pause button returns to 'play' so it seems like a natural thing.
How do I detect the change in audio play/pause state and reflect it back to the app?
回答1:
Here is the demo/test page from the W3C for HTML5 video, but I believe the relative events for you should be the same for audio http://www.w3.org/2010/05/video/mediaevents.html
So you could do something like:
$('audioplayer').on('pause', function() {
if (playerStream.paused) {
playerStream.play();
$('button.toggle-stream').attr('data-icon','s');
}
else {
playerStream.pause();
$('button.toggle-stream').attr('data-icon','p');
}
}
and then do the same for the play event.
Hope that helps
回答2:
Here's a script I've been using for my private internet stream:
$(document).ready(function() {
var player = "#webplayer";
var button = "#webplayer_button";
$(button).click(function() {
if ($(player)[0].paused) {
$(player).attr('src', 'http://www.whateverurl.com/stream.mp3');
$(player)[0].play();
} else {
$(player)[0].pause();
$(player).attr('src', 'media/silence.ogg');
}
});
});
The added functionality of this script is that it loads a small OGG
file which contains only silence when it puts the player to pause. It will then reload the URL
when the player is started later, clearing the player's buffer.
来源:https://stackoverflow.com/questions/17479970/how-do-i-detect-if-html5-audio-play-pause-state-has-been-changed-outside-of-webp