WordPress uses Mediaelement.js for its audio and video player and recently I had to dive in to the code to figure out how to interact with the player using jQuery.

Displaying audio with WordPress and Mediaelement.js is easy enough. All you need is the AUDIO shortcode:

[audio src="http://your-site.com/uploads/audio.mp3]

This hooks into Mediaelement.js automatically and displays a nice audio player on the front end.

Mediaelement.js audio

Since the outputted code uses a unique ID added by Mediaelement.js, I assumed I could use that as my jQuery selector. As you can guess, that didn’t work.

It took some time and a lot of messing around, but I finally figured out that I had to fetch the audio tag before it was processed by Mediaelement.js. That meant using the HTML Audio tag from the source code as my selector.

$( 'audio' )[0]

That will select the first audio tag on a page, which for my purposes, was all I needed.

The full scope of the request was to create a link that skips ahead to a certain section of the audio file. I was able to do this with a few lines of jQuery:

$( 'a.go-to-time' ).click( function(e) {
   e.preventDefault();

   $( 'audio' )[0].player.setCurrentTime( $(this).data( 'time' ) );
   $( 'audio' )[0].player.setCurrentRail();
   $( 'audio' )[0].player.play();
} );

The HTML required for the above script needed to include the DATA attribute within the anchor tag so that a specific time (in seconds) could be set:

<a href="#" data-time="60">Go to 60 second mark and play</a>

In the end, it took me way too long to figure this out, but afterwards, working with WordPress and Mediaelement.js ended up being pretty straightforward.

Be sure to check out the official website for Mediaelement.js to get more information.