从HTML5和JavaScript的视频捕获帧

前端之家收集整理的这篇文章主要介绍了从HTML5和JavaScript的视频捕获帧前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想每5秒从视频中捕获一帧。

这是我的JavaScript代码

  1. video.addEventListener('loadeddata',function() {
  2. var duration = video.duration;
  3. var i = 0;
  4.  
  5. var interval = setInterval(function() {
  6. video.currentTime = i;
  7. generateThumbnail(i);
  8. i = i+5;
  9. if (i > duration) clearInterval(interval);
  10. },300);
  11. });
  12.  
  13. function generateThumbnail(i) {
  14. //generate thumbnail URL data
  15. var context = thecanvas.getContext('2d');
  16. context.drawImage(video,220,150);
  17. var dataURL = thecanvas.toDataURL();
  18.  
  19. //create img
  20. var img = document.createElement('img');
  21. img.setAttribute('src',dataURL);
  22.  
  23. //append img in container div
  24. document.getElementById('thumbnailContainer').appendChild(img);
  25. }

我遇到的问题是生成的第一个两个图像是相同的,持续时间-5秒的图像不会被生成。我发现缩略图是在特定时间的视频帧显示在<视频>标签。 例如,当video.currentTime = 5时,生成帧0的图像。然后视频帧跳到时间5s。所以当video.currentTime = 10时,生成帧5s的图像。

解决方法

原因

问题是寻求视频(通过设置它的currentTime)是异步的。

您需要聆听被请求的事件,否则将冒险采取实际的当前框架,这可能是您的旧价值。

由于它是异步的,所以不能使用setInterval(),因为它是异步的,当下一个框架被查找时,您将无法正确同步。没有必要使用setInterval(),因为我们将使用seekked事件,而不会使所有内容都同步。

通过重写代码,您可以使用被查看的事件来浏览视频以捕获正确的帧,因为此事件确保我们实际上是通过设置currentTime属性在我们请求的帧。

  1. // global or parent scope of handlers
  2. var video = document.getElementById("video"); // added for clarity: this is needed
  3. var i = 0;
  4.  
  5. video.addEventListener('loadeddata',function() {
  6. this.currentTime = i;
  7. });

将此事件处理程序添加到聚会中:

  1. video.addEventListener('seeked',function() {
  2.  
  3. // now video has seeked and current frames will show
  4. // at the time as we expect
  5. generateThumbnail(i);
  6.  
  7. // when frame is captured increase,here by 5 seconds
  8. i += 5;
  9.  
  10. // if we are not passed end,seek to next interval
  11. if (i <= this.duration) {
  12. // this will trigger another seeked event
  13. this.currentTime = i;
  14. }
  15. else {
  16. // Done!,next action
  17. }
  18. });

@L_403_0@

猜你在找的HTML5相关文章