2017-07-31 104 views
0

我創建了一個腳本,允許我從畫布上記錄一個id爲「imacanvas」的視頻。但問題是沒有創建斑點。我認爲問題在於函數handleDataAvailable未被執行。但我不知道爲什麼?MediaRecorder沒有定義斑點

感謝您的幫助:)

var recordedBlobs; 
var recorder; 
var stream; 

function handleDataAvailable(event) { 
    console.log("0"); 
    if (event.data && event.data.size > 0) { 
    recordedBlobs.push(event.data); 
    console.log("1"); 
    } 
} 

function startRecord(){ 
    recordedBlobs = []; 

    var canvas = document.getElementById('imacanvas'); 
    stream = canvas.captureStream(60); 

    try { 
    recorder = new MediaRecorder(stream); 
    } catch (e) { 
    console.error('Exception while creating MediaRecorder: ' + e); 
    alert('Exception while creating MediaRecorder: ' 
     + e + '. mimeType: ' + options.mimeType); 
    return; 
    } 

    recorder.ondataavailable = handleDataAvailable; 
    recorder.start(10); 
} 

function stopRecord() { 
    recorder.stop(); 
    console.log('Recorded Blobs: ', recordedBlobs); 
} 

function download() { 
    var blob = new Blob(recordedBlobs, {type: 'video/webm'}); 
    var url = window.URL.createObjectURL(blob); 
    var a = document.createElement('a'); 
    a.style.display = 'none'; 
    a.href = url; 
    a.download = 'test.webm'; 
    document.body.appendChild(a); 
    a.click(); 
    setTimeout(function() { 
    document.body.removeChild(a); 
    window.URL.revokeObjectURL(url); 
    }, 100); 
} 

回答

0

爲了能夠通過HTMLCanvasElement.captureStream()激活拍攝的流,你需要有初始化它的上下文,並在其上繪製。

這個必須在你致電captureStream()之前完成。

const chunks_before = []; 
 
    const stream_before = c.captureStream(60); 
 
try { const rec_before = new MediaRecorder(stream_before); 
 
    rec_before.ondataavailable = e => chunks_before.push(e.data); 
 
    rec_before.onstop = e => console.log('before : ', chunks_before.length); 
 
    rec_before.start(); 
 
    setTimeout(() => { 
 
    if (rec_before.state === 'recording') 
 
     rec_before.stop(); 
 
    }); 
 
} catch (e) { 
 
    console.log('before failed'); 
 
} 
 

 
// simply doing this allows us to do it 
 
c.getContext('2d').fillRect(0, 0, 20, 20); 
 

 
const chunks_after = []; 
 
const stream_after = c.captureStream(60); 
 
const rec_after = new MediaRecorder(stream_after); 
 
rec_after.ondataavailable = e => chunks_after.push(e.data); 
 
rec_after.onstop = e => console.log('after : ', chunks_after.length); 
 
rec_after.start(); 
 

 
setTimeout(() => { 
 
    if (rec_after.state === 'recording') 
 
    rec_after.stop(); 
 
}, 1000);
<canvas id="c"></canvas>