上传前如何知道音频/视频的持续时间?

wef*_*wef 3 javascript audio video reactjs

我需要使用默认值上传文件(音频/视频),input type='file'并且我应该在 api 请求中传递视频的持续时间,我该如何做到这一点?

  const uploadFile = async (event) => {
    let file = await event.target.files[0];
    //here api POST request where i should pass duration
   }:
Run Code Online (Sandbox Code Playgroud)

lis*_*tdm 5

您可以使用HTMLMediaElement.duration获取音频持续时间:

async function getDuration(file) {
 const url = URL.createObjectURL(file);

 return new Promise((resolve) => {
   const audio = document.createElement("audio");
   audio.muted = true;
   const source = document.createElement("source");
   source.src = url; //--> blob URL
   audio.preload= "metadata";
   audio.appendChild(source);
   audio.onloadedmetadata = function(){
      resolve(audio.duration)
   };
 });
}
Run Code Online (Sandbox Code Playgroud)

然后在你的函数中:

const uploadFile = async (event) => {
   let file = event.target.files[0];
    //here api POST request where i should pass duration
   const duration = await getDuration(file);
 }:
Run Code Online (Sandbox Code Playgroud)