1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JSで動画のアップロード前に尺を取得する

Posted at

やりたいこと

動画をアップロードする前に、フロント側で再生時間に上限を設けたい

完成形

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Video Duration Test</title>
</head>
<body>
<input id="video-input" type="file">
<video id="video" display="none" height=0 width=0 type="video/mp4"></video>

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$('#video').on('loadedmetadata', () => {
  const duration = $('#video')[0].duration
  console.log('duration =', duration, 'seconds')
  if (duration > 3600) {
      alert('Too long!')
  }
})

$('#video-input').change(e => {
  $('#video').attr('src', URL.createObjectURL(e.target.files[0]))
  // このタイミングでは取れない
  // console.log($('#video')[0].duration)
})
</script>
</body>
</html>

解説

  • 動画の再生時間を取得するにはvideo要素のdurationを参照する
  • 見えないvideo要素を用意しておき、inputで選択された動画をsrcに指定する
  • srcを変更した直後にはdurationが取れないため、loadedmetadataイベントを待つ
1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?