从HTML中提取Video信息
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'));
}
获取视频的第一帧作为视频封面
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);
videoElement.addEventListener('loadedmetadata', () => {
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);
const imageData = canvas.toDataURL('image/jpeg');
document.body.removeChild(videoElement);
resolve(imageData)
});
}, { once: true });
videoElement.currentTime = 0;
});
videoElement.onerror = (error) => {
reject(error);
};
videoElement.src = videoUrl;
});
}
获取视频的播放时长
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);
});
}