js获取视频时长

 //获取视频时长
        if (names.indexOf('mp4') > -1) {
          const reader = new FileReader()
          const rs = reader.readAsArrayBuffer(file.file)
          let blob = null
          reader.onload = (e) => {
            if (typeof e.target.result === 'object') {
              blob = new Blob([e.target.result])
            } else {
              blob = e.target.result
            }
            if (blob == null) return
            const url = URL.createObjectURL(blob)
            const audioElement = new Audio(url)
            let duration
            const fun = (duration) => {
              this.duration = duration
              console.log('视频时长:', this.duration)
            }
            //下面需要注意的是在监听loadedmetadata绑定的事件中对duration直接进行赋值是无效的,需要在fun回调函数中进行赋值
            audioElement.addEventListener('loadedmetadata', function () {
              //音频/视频的元数据已加载时,会发生 loadedmetadata 事件
              duration = audioElement.duration //时长以秒作为单位
              fun(parseFloat(duration).toFixed(1))
            })
          }
        }

  

posted @ 2023-04-11 10:22  212的s  阅读(731)  评论(0编辑  收藏  举报