Using MediaElement.js with audio files Media 7.x-1.x

Last updated on
30 August 2018

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

Media module doesn't come with a built-in audio player, but will work with MediaElement.js. MediaElement.js does not provide field formatters for Media 1.x's deprecated Multimedia asset field type, so it takes a bit of work to make them work together.

One approach would be to use hook_field_formatter_info_alter() on MediaElement module's mediaelement_field_formatter_info() to allow it to be used as a Multimedia asset field formatter, or to just write a custom field formatter that would tie Media and MediaElement together. If you want to be able to work with your theme using Display Suite, Panels, or core Fields UI, that might be the way to go.

Another approach is to do everything in the template files. The following code sample assumes you've created a Multimedia asset field for audio called field_audio, with only one value, and nothing translated.

In your theme's template.php (replace 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()));
  }
}

Then in node--NODETYPE.tpl.php (or whichever tpl file is appropriate), insert HTML like this wherever you want the audio player to appear:

<?php if ($audio_player) : ?>
<div class="audio-feature">
<?php print $audio_player; ?>
</div>
<?php endif; ?>

Help improve this page

Page status: No known problems

You can: