To do this in Drupal 7 first install two modules : getID3() and Computed Field.

In the content type that holds the details for each audio track add a field of type 'Computed'
For this field, in the entry 'Computed Field (PHP)' insert the following code:

$node = menu_get_object();

if(!isset($node->nid)){
    //this is to be a new node so get audio file uri from 
    //most recent entry in Drupal's file_managed table
    $name2 = db_query_range('SELECT uri FROM {file_managed} ORDER BY fid DESC',0,1)->fetchField();
}else{
    //this is an existing node being edited so get audio file uri 
    //for this node from Drupal's node table
    $thisname = field_get_items('node', $node, 'field_audiofile');
    $name2 = $thisname[0]['uri'];
}

$fileinfo = getID3_analyze(drupal_realpath($name2));
$playtime_sec = round($fileinfo['playtime_seconds'] / 60);

//Generate playtime in minutes (for display only), @type String
$playtime_mins = $fileinfo['playtime_string'];

$entity_field[0]['value'] = $playtime_sec;

where 'field_audiofile' is the machine name of the field used for the file path of each track
In this case '$playtime' uses PHP code to give the duration of the track in minutes

Comments

JohnRofls’s picture

if(!isset($node->nid)){
    //this is to be a new node so get audio file uri from 
    //most recent entry in Drupal's file_managed table
    $name2 = db_query_range('SELECT uri FROM {file_managed} ORDER BY fid DESC',0,1)->fetchField();

A.) Won't this code break if you have several filefields on the node?
B.) Is there any advantage to using this db_query over just doing the field_get_items()?

jvanja’s picture

For the above code to work for getID3 version 7.x-2.0-beta3 you need to change it to something like this:

$file = file_load($node->your_field_name['und'][0]['fid']);
$fileinfo = getid3_analyze_file($file);

Also $fileinfo['playtime_seconds'] already returns time in seconds so you don't need to divide it by 60. Just do this:

$playtime_sec = round($fileinfo['playtime_seconds']);
KyleNakhul’s picture

How do I do this in Drupal 8? I have installed both modules but I'm unable to get it to work.