Get media (mp3) duration

Thank you Sunnyson for this help!
I took a different approach but with the same logic, with the help of Raoul Kramer.
I post the code here if anyone will need it in the future.

  1. Creating a duration field in the model

  2. Installing the "got package (npm install got --save)

  3. Using this code in the mian/api/song/model/song.js
    Change the name of the model to whatever you need, in my example it’s model.media

    ‘use strict’;

    const mm = require(‘music-metadata’);
    const got = require(‘got’);

    async function getMp3Metadata(pathOrUrl, parseOption = { duration: true, skipCovers: true }) {
    if (pathOrUrl.startsWith(‘http’)) {
    const body = await got(pathOrUrl).buffer();
    if (body) {
    return await mm.parseBuffer(body, ‘audio/mpeg’, { duration: true, skipCovers: true });
    }
    }
    // This is for AWS absolute URL
    return await mm.parseFile($pathOrUrl, parseOption); //on local file uploads use: return await mm.parseFile(./public/${pathOrUrl}, parseOption); and figure out where the upload directory is stored and replace ./public/
    }

    /**
    // Read the documentation (Strapi’s documentation | Strapi Documentation)
    //to customize this model
    */

    module.exports = {
    lifecycles: {
    async beforeCreate(model) {
    if (model.media) {
    const file = await strapi.plugins[‘upload’].services.upload.fetch({ id: model.media });
    const mp3Meta = await getMp3Metadata(file.url);
    model.duration = mp3Meta.format.duration;
    model.title = mp3Meta.common.title;
    }
    },
    async beforeUpdate(params, model) {
    if (model.media) {
    const file = await strapi.plugins[‘upload’].services.upload.fetch({ id: model.media });
    const mp3Meta = await getMp3Metadata(file.url);
    model.duration = mp3Meta.format.duration;
    model.title = mp3Meta.common.title;
    }
    }
    }
    };

This will parse the mp3 file and get its duration on every update or creation of a new record.

Good luck!