Home > other >  How can I get video duration from raw video file in React?
How can I get video duration from raw video file in React?

Time:03-25

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;

CodePudding user response:

You can use media.duration to find out the duration of the video/audio file.

let media = new Audio(videoFile);
media.onloadedmetadata = function(){
  media.duration; // this would give duration of the video/audio file
}; 

CodePudding user response:

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} onl oadedMetadata={handleLoadedMetadata} />
    </div>
  );
};

Learn more about HTML5 video element

  • Related