Working with WordPress and Mediaelement.js

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:


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:

Go to 60 second mark and play

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.

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie