3

My need is to get the duration OR time length of this video file. So I did console.log(videoFile.duration) but its show undefined & why does it show undefined? So how can I get video duration in React js...

const VideoList = ({ videoFile }) => {

  console.log(videoFile.duration);
  // output ==> undefined

  return (

      <div className="relative">

        <video src={videoFile} className="w-full pb-2 sm:w-32 sm:pb-0 rounded mr-2" />

        <span className="absolute bottom-1 right-3 bg-black/60 text-white rounded px-1.5">0:00</span>

      </div>
  );
}

export default VideoList;
hangindev.com
  • 4,573
  • 12
  • 28
taiseen
  • 246
  • 1
  • 4
  • 11

1 Answers1

9

You may add a loadedmetadata event handler to the video element. When the event is fired, the duration and dimensions of the media and tracks are known.

const MyVideo = ({ src }) => {
  const videoEl = useRef(null);

  const handleLoadedMetadata = () => {
    const video = videoEl.current;
    if (!video) return;
    console.log(`The video is ${video.duration} seconds long.`);
  };

  return (
    <div>
      <video src={src} ref={videoEl} onLoadedMetadata={handleLoadedMetadata} />
    </div>
  );
};

Learn more about HTML5 video element

hangindev.com
  • 4,573
  • 12
  • 28
  • 1
    Thank you so much... it's working... & also learned a new way of thinking about this kind of situation if it happens again. – taiseen Mar 25 '22 at 07:06