動画の再生に合わせて、現在の再生時間を取得するには、timeupdateイベントを使用します。このイベントは、動画の再生位置が変更されたときに発生します。
以下は、JavaScriptを使用して、動画の再生に合わせて現在の再生時間を取得するコード例です。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<video id="my-video" width="640" height="360" controls>
<source src="./video.mp4" type="video/mp4">
</video>
<p id="current-time"></p>
<script src="./index.js"></script>
</body>
</html>
const video = document.getElementById('my-video');
const currentTimeText = document.getElementById('current-time');
video.addEventListener('timeupdate', () => {
const currentTime = video.currentTime;
const minutes = Math.floor(currentTime / 60);
const seconds = Math.floor(currentTime % 60);
const currentTimeString = `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
currentTimeText.textContent = `Current Time: ${currentTimeString}`;
});
このコードでは、まずvideo要素と表示するためのp要素を取得しています。次に、video要素の timeupdate
イベントをリッスンして、現在の再生時間を取得し、mm:ss形式で表示するためのテキストを生成します。最後に、p要素のtextContentにテキストを設定して、現在の再生時間を表示します。
注意点として、動画の再生時間は、秒単位で少数まで取得されるため、mm:ss形式に変換するために、Math.floorを使用して、分と秒を取得しています。最後に、テキストを生成する際に、三項演算子を使用して、秒数が1桁の場合にゼロを追加するようにしています。