なんでもノート

なんでも書くノートみたいなブログ

<video>に読み込んだ動画の秒数を取得する

<input type="file">で選択したファイルのサイズを取得する - なんでもノート に続きtips2個目。video要素に読み込んだ動画の秒数を取得する方法。durationchangeイベント発生時にdurationから読み取れる。以下、React + TypeScriptのサンプルコード。

import React, { useRef } from "react";

// …(略)… 

const ref = useRef<HTMLVideoElement>(null);

const onChangeVideoDuration = () => {
  if (ref.current) {
    const videoDuration = ref.current.duration;
    console.log(videoDuration);
  }
}

// 任意のタイミングでsrcを変更する
const onXXX = () => {
  if (ref.current) {
    ref.current.src = "sample.mp4";
    ref.current.addEventListener("durationchange", onChangeVideoDuration, { once: true });
  }
}

// …(略)…

<video ref={ref} />