can you explain me how to obtain Duration and length of a media file?

Created on 23 April 2025, 22 days ago

Problem/Motivation

Hello,
I have almosted finished mapping all fields.
There are 2 fields that really I don't know how to handle, because it is not clear to me how obtain mediaMetadata. I am not a programmer, but I like this module, it is what I need.
What do you use to obtain length, size, etc?
Thank you!

💬 Support request
Status

Active

Version

1.10

Component

Documentation

Created by

🇮🇹Italy drein

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @drein
  • 🇮🇹Italy drein

    ah, I'm on drupal11

  • 🇮🇹Italy drein

    ok, I write this for people that could have same problem.
    The solution that I have found is to write a custom module.
    Ok, Deepseek writes it for me, I adjust it and you can use this solution and works:

    1.
    First of all create 2 field in your content type, filesize and duration, they should be numbers.

    2. The module require getid3, so:

    composer require james-heinrich/getid3
    

    3. Create a subdirectory into modules/custom and call it for example audiometadatahelper.
    Put there 2 files, audiometadatahelper.info.yml and audiometadatahelper.module.

    4.
    Content of audiometadatahelper.info

    name: audioMetadata Helper
    description: 'provides the values of size and duration and writes them in the fields'
    type: module
    core_version_requirement: ^11
    package: Custom
    
    

    5. Content of audiometadatahelper.module

    <?php
    
    use Drupal\Core\Entity\EntityInterface;
    use Drupal\media\MediaInterface;
    use Drupal\file\FileInterface;
    
    /**
     * Implements hook_entity_presave().
     */
    function audiometadatahelper_entity_presave(EntityInterface $entity) {
      // Verify it is a podcast content type
      if ($entity->getEntityTypeId() === 'node' && $entity->bundle() === 'podcast') {
        // Load media audio (field_file_audio) field
        if ($entity->hasField('field_file_audio') && !$entity->get('field_file_audio')->isEmpty()) {
          $media_entity = $entity->get('field_file_audio')->entity;
          
          if ($media_entity instanceof MediaInterface) {
            // File field in the media Type(modify if necessary)
            $media_file_field = 'field_media_audio_file';
            if ($media_entity->hasField($media_file_field)) {
              $audio_file = $media_entity->get($media_file_field)->entity;
              
              if ($audio_file instanceof FileInterface) {
                // 1. Save the file size
                if ($entity->hasField('field_filesize')) {
                  $entity->set('field_filesize', $audio_file->getSize());
                }
                
                // 2. Calculate and save the duration
                if ($entity->hasField('field_duration')) {
                  $uri = $audio_file->getFileUri();
                  $duration = audiometadatahelper_get_audio_duration($uri);
                  $entity->set('field_duration', $duration);
                }
              }
            }
          }
        }
      }
    }
    
    /**
     * Extract the duration of audio using Getid3.
     */
    function audiometadatahelper_get_audio_duration($uri) {
      $realpath = \Drupal::service('file_system')->realpath($uri);
      
      if (class_exists('getID3')) {
        $getID3 = new getID3();
        try {
          $file_info = $getID3->analyze($realpath);
          return $file_info['playtime_seconds'] ?? 0;
        } catch (\Exception $e) {
          \Drupal::logger('audiometadatahelper')->error('Errore analisi audio: @error', ['@error' => $e->getMessage()]);
        }
      }
      
      return 0;
    }
    
    

    6. Install the module and enjoy! When you upload a file and save the content, filesize and duration will be populated, so you can map them from the podcast module.

    Finally, I want to clarify that I am absolutely not a programmer. I just found a solution that works for me.
    Maybe I hope to help others and save their hours of study.

Production build 0.71.5 2024