我在我的React应用程序中使用视频js。我正在从视频URL而不是从本地计算机流式传输视频。我有一个提供给播放器的视频网址。我想从视频中捕获/提取一些帧
问题:假设我的超时时间分别为20秒和30秒。我想在20到30秒之间随机提取4帧。我不希望在播放20秒视频时将其提取出来。我想在页面加载后立即提取框架。
这是我尝试过的
async componentDidMount() {
this.init()
timeline_width = document.getElementById("timeline").offsetWidth
let frames = await this.extractFramesFromVideo(this.props.video_reducer.selected_video_file);
}
async extractFramesFromVideo(videoUrl, fps=25) {
return new Promise(async (resolve) => {
// fully download it first (no buffering):
let videoBlob = await fetch(videoUrl).then(r => r.blob());
let videoObjectUrl = URL.createObjectURL(videoBlob);
let video = document.createElement("video");
let seekResolve;
video.addEventListener('seeked', async function() {
if(seekResolve) seekResolve();
});
video.addEventListener('loadeddata', async function() {
let canvas = document.getElementById('prevImgCanvas');
let context = canvas.getContext('2d');
let [w, h] = [video.videoWidth, video.videoHeight]
canvas.width = w;
canvas.height = h;
let frames = [];
let interval = 1 / fps;
let currentTime = 0;
let duration = video.duration;
while(currentTime < duration) {
video.currentTime = currentTime;
await new Promise(r => seekResolve=r);
context.drawImage(video, 0, 0, w, h);
let base64ImageData = canvas.toDataURL();
frames.push(base64ImageData);
currentTime += interval;
}
resolve(frames);
});
// set video src *after* listening to events in case it loads so fast
// that the events occur before we were listening.
video.src = videoObjectUrl;
});
}
但这会提取视频的所有帧。我只想要特定的帧。
有人可以建议解决方案吗?
答案 0 :(得分:1)
假设您必须从下面的视频中获取静止图像,
<video id="video" controls="controls">
<source src=".mp4" />
</video>
<button id="capture">Capture</button>
<div id="output"></div>
使用以下功能从视频中获取图像,然后再加载:
(function() {
"use strict";
var video, $output;
var scale = 0.25;
var initialize = function() {
$output = $("#output");
video = $("#video").get(0);
$("#capture").click(captureImage);
};
var captureImage = function() {
var canvas = document.createElement("canvas");
canvas.width = video.videoWidth * scale;
canvas.height = video.videoHeight * scale;
canvas.getContext('2d')
.drawImage(video, 0, 0, canvas.width, canvas.height);
var img = document.createElement("img");
img.src = canvas.toDataURL();
$output.prepend(img);
};
$(initialize);
}());
感谢Chris Brandsma,我已在wordpress上将此代码用作自定义代码,并根据我的工作进行了一些更改,因此您需要添加一些代码以获取基于随机时间的图像。 您可以在以下位置找到此代码:Tutorial Code