上传时如何获取多个视频的持续时间?

how to get duration of multiple video while uploading?

<!DOCTYPE html>
<html>
<body onload="myFunction()">

<input type="file" id="myFile" multiple size="50" onchange="myFunction()">

<p id="demo"></p>

<script>
function myFunction(){
    var x = document.getElementById("myFile");
    var txt = "";
    if ('files' in x) {
        if (x.files.length == 0) {
            txt = "Select one or more files.";
        } else {
            for (var i = 0; i < x.files.length; i++) {
                txt += "<br><strong>" + (i+1) + ". file</strong><br>";
                var file = x.files[i];
                if ('name' in file) {
                    txt += "name: " + file.name + "<br>";
                }
                if ('size' in file) {
                    txt += "size: " + file.size + " bytes <br>";
                }
            }
        }
    } 
    else {
        if (x.value == "") {
            txt += "Select one or more files.";
        } else {
            txt += "The files property is not supported by your browser!";
            txt  += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead. 
        }
    }
    document.getElementById("demo").innerHTML = txt;
}
</script>

<p><strong>Tip:</strong> Use the Control or the Shift key to select multiple files.</p>

</body>
</html>

在此,他们列出了视频文件名和大小。但是如何列出所有用文件名上传的视频的时长和文件 size.i 可以在上传时获取单个视频时长。但是当它有多个视频时很难找到。

您需要将文件"load" 放入视频节点并等待加载文件的元数据并从加载的节点中提取持续时间。这是一个从 file 获取持续时间的函数。注意这个函数 returns 一个 promise:

function getDuration(file) {
  let videoNode = document.createElement("video");
  let promise = new Promise(function(resolve, reject) {
    videoNode.addEventListener("loadedmetadata", function() {
      resolve(videoNode.duration);
    });
    videoNode.addEventListener("error", function() {
      reject(videoNode.error.message + "(" + videoNode.error.code + ")");
    });
  });

  const URL = window.URL || window.webkitURL;
  videoNode.src = URL.createObjectURL(file);

  return promise;
}

然后您可以像这样调用此函数:

getDuration(file).then((duration) => {
  // duration in seconds (as float)
});

注意! 在连接 txt 变量并输出它之前,您需要重新实现循环以等待承诺完成。