H5页面在IOS微信webview中无法校验视频文件时长问题

因业务需求需要一个图片视频文件上传功能,需支持主流浏览器及微信钉钉内置浏览器,遂考虑用一个简单的H5页面做上传客户端。视频上传因为要控制视频长度,在其他浏览器中都校验通过,但是在微信中却出了问题

const beforeRead = (file)=> {
      return new Promise((resolve,reject)=>{
        if(props.type == 'video'){
          let url = URL.createObjectURL(file)
          let audioElement = new Audio(url)
          audioElement.addEventListener("loadedmetadata", ()=>{
            let audioDuration = audioElement.duration;
            if(audioDuration>60){
              Toast(`仅支持上传1分钟时长以内视频`)
              reject()
            }else{
              resolve(file)
            }
          })
        }else{
          if (!['image/jpeg','image/png'].includes(file.type)) {
            Toast('所选文件格式不支持');
            reject()
          }else{
            resolve(file)
          }
        }
      })
    }

问题原因:IOS微信浏览器需要播放视频才能通过监听loadedmetadata事件获取视频长度,以下是解决办法:

const beforeRead = (file)=> {
      return new Promise((resolve,reject)=>{
        if(props.type == 'video'){
          let url = URL.createObjectURL(file)
          let audioElement = new Audio(url)
          audioElement.muted = true
          audioElement.play().then(()=>audioElement.pause())
          audioElement.addEventListener("loadedmetadata", ()=>{
            let audioDuration = audioElement.duration;
            if(audioDuration>60){
              audioElement.muted = false
              Toast(`仅支持上传1分钟时长以内视频`)
              reject()
            }else{
              audioElement.muted = false
              resolve(file)
            }
          })
        }else{
          if (!['image/jpeg','image/png'].includes(file.type)) {
            Toast('所选文件格式不支持');
            reject()
          }else{
            resolve(file)
          }
        }
      })
    }

H5页面vue3.0+vant,参见upload组件不再赘述!


版权声明:本文为V_AYA_V原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。