js实现视频定点时间段截屏

11 篇文章 0 订阅

前段时间做的一个需求,根据字幕文件提供的每一句字幕开始时间对该时间的视频画面截屏,记录一下实现。不过感觉还是交给后端做比较好,

<template>
  <div class="home-page">
    <div class="upload">
      <Upload
        multiple
        type="drag"
        style="width:200px"
        :before-upload="UploadVideo"
        action=""
      >
        <div style="padding: 20px 0">
          <Icon type="ios-cloud-upload" size="52" style="color: #24345f"></Icon>
          <p>点击或拖拽上传</p>
        </div>
      </Upload>
    </div>
    <div class="myCover">
      <div class="pic" v-for="(item, index) in showCoverArr" :key="index">
        <img :src="item" />
      </div>
    </div>
  </div>
</template>
  data() {
    return {
      cutTime: ['3', '20', '66'],//截图时间点,最好采用% ,根据%×进度得到播放时间
      showCoverArr: [], //截图后生成的base64数组
    };
  },
    //上传文件
    UploadVideo(file) {
      this.showCoverArr = [];
      console.log(file);
      if (!/^video\/mp4$/.test(file.type)) {
        this.$Message.warning("视频格式不正确,只支持“.mp4”");
        return false;
      }
      if (file.size / 1024 / 1024 > 100) {
        this.$Message.warning("视频大小不能超过100M");
        return false;
      }
      let url = URL.createObjectURL(file);
      this.videoInfo.src = url;
      console.log(url);
      this.cutVideoCover(url, 0);
    },
    // 视频封面截图(传入截屏时间点)
    cutVideoCover(url, index) {
      utilsTool.GetVideoCover({
        url: url,
        time: this.cutTime[index],
        success: (res) => {
          this.showCoverArr.push(res.base64); //给展示列表传入截图的URL
          console.log(
            "第",index+1,"张",
            "总",this.cutTime.length,"张"
          );
          if(parseInt(index)<parseInt(this.cutTime.length)){
            this.cutVideoCover(url, index+=1);
          }else {
            console.log(this.showCoverArr)
          }
        },
      });
    },

效果预览
bilibili视频演示地址
在这里插入图片描述

utilsTool封装

//压缩图片
function clipAndCompressCover({
  media,
  currentWidth,
  currentHeight,
  success
}) {
  // eslint-disable-next-line no-unused-vars
  const that = this;
  const canvas = document.createElement("canvas");
  const area = canvas.getContext("2d");
  const currentScale = currentWidth / currentHeight;
  const targetScale = 750 / 420;
  let targetWidth = 0;
  let targetHeight = 0;
  let clipWidth = 0;
  let clipHeight = 0;
  let quality = 0.95; // 不要用1,会额外增大base64大小。

  // 根据视频宽高,决定截图大小
  if (currentScale >= targetScale) {
    targetHeight = currentHeight > 420 ? 420 : currentHeight;
    targetWidth = targetHeight * currentScale;
  } else {
    targetWidth = currentWidth > 750 ? 750 : currentWidth;
    targetHeight = targetWidth / currentScale;
  }
  clipWidth = targetWidth > 750 ? 750 : targetWidth;
  clipHeight = targetHeight > 420 ? 420 : currentHeight;
  canvas.width = clipWidth;
  canvas.height = clipHeight;

  area.drawImage(
    media,
    (clipWidth - targetWidth) / 2,
    (clipHeight - targetHeight) / 2,
    targetWidth,
    targetHeight
  );
  var handler = function () {
    const base64 = canvas.toDataURL("image/jpeg", quality);
    getMediaSize({
      src: base64
    }).then(response => {
      if (response.size / 1024 > 100) {
        quality -= 0.1;

        if (quality > 0.2) {
          handler();
        }
      } else {
        success && success(base64);
      }
    });
  };
  handler();
}

//绘制视频封面图片
const GetVideoCover = ({
  url,
  time,
  success
}) => {
  const video1 = document.createElement("video");
  video1.src = url;
  video1.style.cssText = "position:fixed; top:0; left:-100%; visibility:hidden";
  video1.onloadeddata = function () {
    let currentTime = time; //截图时间点
    video1.addEventListener("timeupdate", function () {
      clipAndCompressCover({
        media: video1,
        currentWidth: video1.videoWidth,
        currentHeight: video1.videoHeight,
        success: function (base64) {
          video1.remove(video1);
          success({
            base64: base64
          })
        }
      });
    });
    video1.currentTime = currentTime < 0 ? 1 : currentTime;
  };
  // edge浏览器必须要追加到dom中,才能顺利执行相关事件。
  document.body.appendChild(video1);
};

// 获取媒体资源的大小,返回一个Promise对象。用于解决无法直接获取视频或图片的文件大小。
function getMediaSize({
  src
}) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();

    // eslint-disable-next-line no-unused-vars
    xhr.onreadystatechange = _ => {
      if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
          resolve({
            size: xhr.response.size
          });
        } else {
          reject();
        }
      }
    };

    xhr.open('get', URL.createObjectURL(transformBase64ToBlob(src)));
    xhr.responseType = 'blob';
    xhr.send();
  });
}

function transformBase64ToBlob(base64) {
  let byteString;

  if (base64.split(',')[0].indexOf('base64') >= 0) {
    byteString = atob(base64.split(',')[1]);
  } else {
    byteString = unescape(base64.split(',')[1]);
  }

  const mimeString = base64.split(',')[0].split(':')[1].split(';')[0];
  const ia = new Uint8Array(byteString.length);

  for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }

  const blob = new Blob([ia], {
    type: mimeString
  });

  return blob;
}
export default {
  GetVideoCover,
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值