Display an audio player in Drupal using Media and MediaElement.js modules

I'm currently working on a new Drupal site with a lot of media: slideshows, movies, and audio. I'm taking the opportunity to use the much-in-development Media module. Because this site needs to go up soon, I'm using the more stable 7.x-1.2. It's a much more robust way of working with rich media than anything Drupal has had previously, but there are some things that need some extra work, like display of uploaded MP3s and movie files (as opposed to embedded media from other sites).

The site I'm working on is leveraging Vimeo for movies, which saves a lot of work and bandwidth, but audio files are uploaded directly, so we need a player. We're using MediaElement.js, a really nice HTML5-based player with fallbacks for Flash and so on. It's pretty easy to customize how it looks, and it works well. There is also a Drupal module for MediaElement. There's no direct integration between Media 7.x-1.2 and MediaElement module that I find, so I had to do a bit of looking to figure out a good way to embed the audio player in my custom theme.

I've just posted a page on using Media and MediaElement modules with audio files in the Drupal community documentation, but here's a quick recap. This solution is intended for Drupal themer's comfortable with the use of preprocess functions in PHP template files.

Code like this goes in your theme's template.php file (replacing YOURTHEME with the name of your theme):

function YOURTHEME_preprocess_node(&$variables, $hook) {
  $node = $vars['node'];

  // if there is an audio file available
  if (isset($node->field_audio['und'][0]['fid'])) {
    // field_audio stores the fid - load the file object
    $audio_file = file_load($node->field_audio['und'][0]['fid']);

    // set up the attributes to be sent to theme_mediaelement_audio()
    $audio_attrs = array(
      // the audio src, e.g. public://audio.mp3
      'src' => file_create_url($audio_file->uri),
      // set the width to whatever is appropriate for your site
      'width' => '100%',

    // create the HTML to insert in the template file using theme_mediaelement_audio()
    $vars['audio_player'] = theme('mediaelement_audio', array('attributes' => $audio_attrs, 'settings' => array()));

Having done this, you now have the $audio_player variable available in your node.tpl.php file and related files (like node--audio.tpl.php if you have an audio content type). You could use it this way:

<?php if ($audio_player) : ?>
<div class="audio-feature">
<?php print $audio_player; ?>
<?php endif; ?>
Comments are closed on this post to keep spammers at bay. If you want to chime in, please email or send a tweet.