从HTML中提取Video信息
javascript
/**
* 从html字符串中提取video标签
* 入参: {String} htmlString
* 出参:{Array} 数组
*/
function extractVideosFromHTML(htmlString) {
const dom = new DOMParser().parseFromString(htmlString, 'text/html');
const videos = Array.from(dom.querySelectorAll('video'));
return videos.map(videoElement => videoElement.getAttribute('src'));
}
获取视频的第一帧作为视频封面
javascript
/**
* 获取视频的第一帧
* 入参:视频文件的url地址
* 返回第一帧图片
*/
function getFirstVideoFrame(videoUrl) {
return new Promise((resolve, reject) => {
const videoElement = document.createElement('video');
videoElement.crossOrigin = 'anonymous';
videoElement.muted = true; // 可选,静音视频防止音频自动播放问题
videoElement.style.display = 'none'; // 隐藏视频元素
document.body.appendChild(videoElement); // 添加到DOM中以便加载
videoElement.addEventListener('loadedmetadata', () => {
// 设置canvas大小与视频一致
const canvas = document.createElement('canvas');
canvas.width = videoElement.videoWidth;
canvas.height = videoElement.videoHeight;
const ctx = canvas.getContext('2d');
videoElement.addEventListener('seeked', async () => {
// 移动到视频开始位置并绘制第一帧
ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
// 转换canvas内容为Data URL
const imageData = canvas.toDataURL('image/jpeg'); // 或'image/png'
// 清理DOM
document.body.removeChild(videoElement);
resolve(imageData)
});
}, { once: true });
// 快速跳转至视频开始处
videoElement.currentTime = 0;
});
videoElement.onerror = (error) => {
reject(error); // 如果加载视频出错,返回Promise的reject值
};
videoElement.src = videoUrl;
});
}
获取视频的播放时长
javascript
/**
* 获取视频的时长
* 入参:视频文件,file对象
* 返回: 视频时长,单位为 秒
*/
function getVideoDuration(file) {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.onload = (event) => {
const blob = new Blob([event.target.result], {type: file.type});
const video = document.createElement('video');
video.src = URL.createObjectURL(blob);
video.onloadedmetadata = () => {
resolve(video.duration);
URL.revokeObjectURL(video.src);
video.remove();
};
video.onerror = (err) => {
URL.revokeObjectURL(video.src);
video.remove()
reject(err)
}
};
fileReader.readAsArrayBuffer(file);
});
}