乐趣区

关于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>
  <input type="file" onchange="changeFile(event)" />
  <script>
    async function changeFile(e) {console.log(e)
      let files = e.target.files
      console.log(files)
      console.log(await checkSize(files, 120), '校验胜利为 true 失败为 false、120 示意 120 秒');
    }
    let checkSize = async (files, size) => {// console.log(56, Number.isNaN(Number(size)), size)
      if (!files || !files[0]) return false
      // 这一条是正式服务器不须要这段所以当 size 为 undefined 时默认 返回 true
      if (Number.isNaN(Number(size))) return true
      const checktimevideo = document.getElementById('checktimevideo')
      if (checktimevideo) {document.body.removeChild(checktimevideo)
      }
      const video = document.createElement('video')
      const url = URL.createObjectURL(files[0])
      video.src = url
      video.id = 'checktimevideo'
      video.style.display = 'none'

      document.body.appendChild(video)

      return await gettime(video, size)
    }
    let gettime = (video, size) => {
      const promise = new Promise(resolve => {
        video.addEventListener('canplaythrough', e => {console.log('就可视对讲', e, e.target.duration, size)
          if (e.target.duration <= size) {resolve(true)
          } else {resolve(false)
          }
        })
      })
      return promise
    }
  </script>
</body>
</html>
退出移动版