2013-10-04 55 views
28

我想每5秒從視頻捕捉一幀。使用HTML5和JavaScript從視頻捕獲幀

這是我的JavaScript代碼:

video.addEventListener('loadeddata', function() { 
    var duration = video.duration; 
    var i = 0; 

    var interval = setInterval(function() { 
     video.currentTime = i; 
     generateThumbnail(i); 
     i = i+5; 
     if (i > duration) clearInterval(interval); 
    }, 300); 
}); 

function generateThumbnail(i) {  
    //generate thumbnail URL data 
    var context = thecanvas.getContext('2d'); 
    context.drawImage(video, 0, 0, 220, 150); 
    var dataURL = thecanvas.toDataURL(); 

    //create img 
    var img = document.createElement('img'); 
    img.setAttribute('src', dataURL); 

    //append img in container div 
    document.getElementById('thumbnailContainer').appendChild(img); 
} 

我是生成的第一兩個圖像的問題是相同的,並且不產生持續時間-5第二圖像。我發現縮略圖是在< video>標記中顯示特定時間的視頻幀之前生成的。

例如,當video.currentTime = 5時,生成幀0的圖像。然後視頻幀跳到時間5秒。所以當video.currentTime = 10時,會產生第5幀的圖像。

+1

什麼是theCanvas您generateThumbnail功能?你能否提供這個問題的html標籤更有用?我正在嘗試做同樣的事情,但我不確定應如何在頁面上聲明Canvas。謝謝! – alejosoft

回答

36

原因

的問題是,尋求視頻(通過設置它的currentTime)是異步的。

您需要聆聽seeked事件,否則會冒險考慮可能是您的舊值的實際當前幀。

由於它是異步的,因此它不能使用setInterval(),因爲它也是異步的,並且在下一幀搜索時無法正確同步。沒有必要使用setInterval(),因爲我們將使用seeked事件來代替,這將保持一切都是同步的。

解決方案

通過重新編寫代碼一點,你就可以使用seeked事件經過的視頻捕捉正確的幀作爲本次活動,確保我們,我們實際上是在我們要求通過設置在框架currentTime屬性。

// global or parent scope of handlers 
var video = document.getElementById("video"); // added for clarity: this is needed 
var i = 0; 

video.addEventListener('loadeddata', function() { 
    this.currentTime = i; 
}); 

此事件處理程序添加到方:

video.addEventListener('seeked', function() { 

    // now video has seeked and current frames will show 
    // at the time as we expect 
    generateThumbnail(i); 

    // when frame is captured increase, here by 5 seconds 
    i += 5; 

    // if we are not passed end, seek to next interval 
    if (i <= this.duration) { 
     // this will trigger another seeked event 
     this.currentTime = i; 
    } 
    else { 
     // Done!, next action 
    } 
}); 

Demo here

+2

我試過使用你的代碼。現在我有另一個問題。由於查找,當我通過點擊時間線查看視頻時,圖像也會生成。但我不想那樣。 **編輯**我已經解決了這個問題。謝謝。 – Lin

+0

'video.currentTime = i;'不會爲我引發任何查找事件。 – Michael

+0

@邁克爾當時是否解決了你的問題? – Martian2049