Skip to content

Instantly share code, notes, and snippets.

@LeoEatle
Created September 17, 2019 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LeoEatle/45f49e187624a0862bbf62a35378d617 to your computer and use it in GitHub Desktop.
Save LeoEatle/45f49e187624a0862bbf62a35378d617 to your computer and use it in GitHub Desktop.
screenshot from video
/**
* 处理视频文件,获取封面图和时长
* @author leoeatle
*/
define(function(require, exports, module) {
var userAgent = window.navigator.userAgent;
var isSafari = userAgent.indexOf('Safari') != -1 && userAgent.indexOf('Chrome') == -1;
function getVideoInfo(file, element, callback) {
var duration;
return new Promise(function(resolve, reject) {
var blob = new Blob([file]), // 文件转化成二进制文件
url = URL.createObjectURL(blob); // 转化成url
var initialPlay = false;
var initialSnap = false;
if (file && /video/g.test(file.type)) {
// 这里兼容safari,使用blob url时,需要用source指明文件类型type
var $video = $('<div><video controls><source src="' + url + '" type="' + file.type + '"></video></div>');
// 后面加一个空格div是为了解决在富文本中按Backspace时删除无反应的问题
element.html($video);
var videoElement = $video.find('video')[0];
function takeSnap(_event) {
console.log('触发事件', _event);
if (initialSnap) {
return;
}
if (!initialPlay) {
duration = videoElement.duration;
// 先跳到一半的进度再截图
videoElement.currentTime = duration / 2;
initialPlay = true;
} else {
// 延迟一拍再截图
setTimeout(function() {
var canvas = document.createElement('canvas');
canvas.width = videoElement.videoWidth;
canvas.height = videoElement.videoHeight;
canvas.getContext('2d').drawImage(videoElement, 0, 0, canvas.width, canvas.height);
var img = document.createElement('img');
img.src = canvas.toDataURL('image/png');
URL.revokeObjectURL(img.src); // 释放createObjectURL创建的对象
initialSnap = true;
resolve(img);
}, 100);
}
}
videoElement.addEventListener('canplay', takeSnap);
// 这里也是为了兼容safari,因为safari不触发canplay事件
videoElement.addEventListener('canplaythrough', takeSnap);
videoElement.addEventListener('error', function(err) {
reject(new Error(err));
});
} else {
reject(new Error('未获取到文件信息'));
}
}).then(function(img) {
// upload your img
}).then(function(data) {
var thumb_url = data.data.url;
if (!thumb_url) {
throw new Error('GET THUMB_URL ERROR');
}
return {
thumb_url: thumb_url,
duration: duration
};
});
}
module.exports.getVideoInfo = getVideoInfo;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment