Is it playing?

For an installation I’m working on I have auto-playing audio and visual elements which are controlled by user interaction with a physical object. Because of the narrative nature of the elements it is important that the one currently running finishes or is paused before allowing the next one to start. There’s quite a lot of things that you can check for a media element, however for this purpose I’m only really interested in two properties: currentTime and paused. Because I’m using jQuery I need to grab the audio element like this: $('audio_element'). This loads the whole object so if you attempt to access one of its properties you will get undefined. The bit I actually need is located in the [0] position in the object, now if I access one of the properties of the element I get the actual property returned. So, lets check if the audio is currently running according to my rules:

var media = $('audio_element')[0]

if ( media.currentTime === 0 || media.paused ) {
    // do something
}

pretty simple huh? This works under all circumstances for this particular set of rules:

  • if there’s no audio loaded then currentTime returns 0 and paused returns true
  • if the audio has been stopped then paused returns true
  • if the audio has started currentTime is not 0 therefore the code in block doesn’t run.

If you’re going to be using something like this a lot you might want to define .playing as a custom property for all media types:

Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
    get: function(){
        return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
    }
})

If you do this you can then use media.playing to work out if the audio/video element is currently playing. This is particularly useful in embedded systems where you want the elements of your work to interact with each other in defined ways and not just end up with either a horrible cacophony or frustrated viewers who’ve accidentally stopped the thing they were listening to in the middle and now can’t restart it from the same point.

Disclosure

As an Amazon Associate I earn from qualifying purchases.