Jody Heavener Jody Heavener - 3 months ago 9
jQuery Question

How do I detect if HTML5 audio play/pause state has been changed outside of webpage?

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?

Answer

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