input上传视频,获取时长

162 阅读1分钟
const videoRef = useRef() // 绑定input

const handleUpload = async (event) => { // 上传视频
    // file 为上传的视频二进制文件
    const file = event.target.files[0]
    const { type } = file
    if (!/^video\//.test(type)) {
      Toast.info('请上传视频', 2)
      return
    }
    // 处理不能重复上传同一文件的问题
    if (videoRef.current) video.current = ''
    
    let audioElement = new Audio(URL.createObjectURL(file))

    // ios无法触发loadedmetadata,所以要静音播放
    audioElement.muted = true
    audioElement.play().then(() => audioElement.pause())
    audioElement.addEventListener('loadedmetadata', async (_event) => {
      const seconds = parseInt(audioElement.duration) // 时长为秒,小数,182.36
      console.log('----seconds', seconds)
    })
  }


<input
    className={cn.input}
    type={'file'}
    accept={'video/*'}
    ref={videoRef}
    onChange={(e) => handleUpload(e)}
  />

audio语音在ios下获取不到duration总时长问题