Skip to content Skip to sidebar Skip to footer

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

Solution 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


Solution 2:

Events pause and play are fired individually, so you need to listen to both of them and use one event listener to handle your logic.

jQuery example:
$('#audioplayer').on('pause play', function(e) {
    if (e.currentTarget.paused) {
        // ...
    } else {
        // ...
    }
});

For React, make it as a controlled component just like you're doing to other input elements.

const AudioTrack: FC<{ src: string }> = ({ src }) => {
  const [paused, setPaused] = useState<boolean>(true)

  const onAudioStateChange = useCallback((e: SyntheticEvent<HTMLAudioElement>) => {
    setPaused(e.currentTarget.paused)
  }, [])

  console.log(paused)

  return (
    <>
      {/* ..... */}
      <audio src={src} onPlay={onAudioStateChange} onPause={onAudioStateChange} />
    </>
  )
}

Solution 3:

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.


Post a Comment for "How Do I Detect If HTML5 Audio Play/pause State Has Been Changed Outside Of Webpage?"