如何在 JavaScript 中检查上传视频的长度/持续时间

How to Check Length / Duration of an Uploaded Video in JavaScript

本文关键字:视频 持续时间 JavaScript 检查      更新时间:2023-09-26

有没有办法检查用户上传的视频文件的长度?

试。duration ,但这似乎仅适用于 DOM 中已引用的托管视频。

这样的事情怎么样?

// create the video element but don't add it to the page
var vid = document.createElement('video');
document.querySelector('#input').addEventListener('change', function() {
  // create url to use as the src of the video
  var fileURL = URL.createObjectURL(this.files[0]);
  vid.src = fileURL;
  // wait for duration to change from NaN to the actual duration
  vid.ondurationchange = function() {
    alert(this.duration);
  };
});
<input type="file" id="input">

视频文件需要由实际播放器解码才能确定持续时间。JavaScript 只能计算字节数。