获取视频时长,单位s

/**
 * 获取视频时长,单位s
 * how to use
 * getVideoDuration('https://xx.xxx.mp4').then(res=>{
 *     console.log("视频时长",res)
 * })
 */
export function getVideoDuration(url) {
  let ua = navigator.userAgent.toLowerCase();
  let isWx = ua.match(/MicroMessenger/i) == 'micromessenger'; //微信端
  let u = navigator.userAgent;
  let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios手机终端

  if (isWx && isiOS) {
    // IOS的微信环境无法触发onloadedmetadata,需要处理
    return new Promise((reslove) => {
      let audio = document.createElement('audio'); //即使是视频文件,这里也不能使用video,需要使用audio代替
      audio.preload = 'metadata';
      audio.src = url;
      audio.muted = true;
      audio.play().then(() => audio.pause());
      audio.onloadedmetadata = () => {
        alert(audio.duration || '666');
        reslove(parseInt(audio.duration.toString(), 10));
        audio = null;
      };
    });
  } else {
    return new Promise((reslove) => {
      let video = document.createElement('video');
      video.preload = 'metadata';
      video.src = url;
      video.onloadedmetadata = () => {
        reslove(parseInt(video.duration.toString(), 10));
        video = null;
      };
    });
  }
}
posted @ 2023-09-18 14:34  huihuihero  阅读(81)  评论(0编辑  收藏  举报