Ogundipe Pelumi
Ogundipe Pelumi

Reputation: 57

How can i get an audio duration of an mp3 file in React

I tried using some npm packages, but they didn't seem to work, i'm actually using React-audio-player, although the player is playing well and displaying the duration, but i want to be able to get the audio duration before playing and rendering it to my playlist.

 <span className="trackTDuration">8:23</span>   

Upvotes: 1

Views: 4406

Answers (2)

xom9ikk
xom9ikk

Reputation: 2289

When using a component from a library, you can pass the onLoadedMetadata props a function where you can get event. And with event.target.duration, get the duration you need.

The code will look something like this:

import React from "react";
import ReactAudioPlayer from 'react-audio-player';

export const Container = () => {
  const handleLoadMetadata = (meta) => {
    const {duration} = meta.target;
    console.log(duration);
  }

  return (
    <div className="container">
      <ReactAudioPlayer
        src="path_to_mp3.mp3"
        autoPlay
        controls
        onLoadedMetadata={handleLoadMetadata}
      />
    </div>
  );
}

Upvotes: 3

Akihito KIRISAKI
Akihito KIRISAKI

Reputation: 1333

You can access audio element through ref (see Advanced Usage). Audio element provides duration as its member.

Upvotes: 1

Related Questions