blog-banner

Drupal 7 Audio Player with Download

  • Drupal 7
  • Drupal Planet
  • Media

Drupal 7 Download File

In this post, I would like to explain how to have a download button for an audio file along with an audio player. My objective was to allow users to play the audio file using a media player and also allow them to download the file using a button.

For this purpose, I created a content type called "Media" with "field_audio" as the audio file field. I chose the Mediafront module for the audio player. I hope setting up the audio player won't be that difficult, so let's move into the coding part.

I used hook_menu() for registering the drupal path to define how the audio download links should be handled.

function kf_menu() {
  $items['download/media/%file'] = array(
    'page callback' => 'kf_download_file',
    'page arguments' => array(2),
    'access arguments' => array('view media'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

The important part of the code is in the menu callback, as this part of the code transfers the file to the client using HTTP.

function kf_download_file($file) {
  if($file) {
    file_transfer($file->uri, array('Content-Type' => 'audio/mpeg', 'Content-Disposition' => 'attachment; filename="' . $file->filename . '"', 'Content-Length' => $file->filesize));
  }
}

Since we told drupal how to handle the "download/media/%file" path, we need to generate a download link for the nodes. I used hook_node_view() to create and display the download link.

function kf_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'media' && $view_mode == 'full') {
    if (isset($node->field_audio[LANGUAGE_NONE][0]) && !empty($node->field_audio[LANGUAGE_NONE][0])) {
      $file = $node->field_audio[LANGUAGE_NONE][0];
      $file_fid = $file['fid'];
      $audio_download = l(t('Download this file'), 'download/media/' . $file_fid, array('attributes' => array('class' => array('audio-download'))));
      $node->content['download_link'] = array(
        "#markup" => $audio_download,
        "#weight" => 10
      );
    }
  }
  return $node;
}

Finally, we need to return the $node in the node_view function. The download link can be styled as required.

Get awesome tech content in your inbox