Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
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
Is the if statement necessary?
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()?
API for getID3 version 7.x-2.0-beta3 changed
For the above code to work for getID3 version 7.x-2.0-beta3 you need to change it to something like this:
Also $fileinfo['playtime_seconds'] already returns time in seconds so you don't need to divide it by 60. Just do this:
Drupal 8
How do I do this in Drupal 8? I have installed both modules but I'm unable to get it to work.