我真的很惊讶你的代码居然能工作。。。
stream
MediaStream
,那么浏览器甚至不应该知道需要下载的大小,因此不应该知道何时停止下载(这是一个流)。
MediaRecorder#ondataavailable
将以
data
const stream = getCanvasStream(); // we'll use a canvas stream so that it works in stacksnippet
const chunks = []; // this will store our Blobs chunks
const recorder = new MediaRecorder(stream);
recorder.ondataavailable = e => chunks.push(e.data); // a new chunk Blob is given in this event
recorder.onstop = exportVid; // only when the recorder stops, we do export the whole;
setTimeout(() => recorder.stop(), 5000); // will stop in 5s
recorder.start(1000); // all chunks will be 1s
function exportVid() {
var blob = new Blob(chunks); // here we concatenate all our chunks in a single Blob
var url = URL.createObjectURL(blob); // we creat a blobURL from this Blob
var a = document.createElement('a');
a.href = url;
a.innerHTML = 'download';
a.download = 'myfile.webm';
document.body.appendChild(a);
stream.getTracks().forEach(t => t.stop()); // never bad to close the stream when not needed anymore
}
function getCanvasStream() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
// a simple animation to be recorded
let x = 0;
const anim = t => {
x = (x + 2) % 300;
ctx.clearRect(0, 0, 300, 150);
ctx.fillRect(x, 0, 10, 10);
requestAnimationFrame(anim);
}
anim();
document.body.appendChild(canvas);
return canvas.captureStream(30);
}
URL.createObjectURL(MediaStream)
用于
<video>
元素。但这也给浏览器关闭物理设备访问带来了一些困难,因为BlobURLs的生存期可能比当前文档更长。
createObjectURL
使用MediaStream,并且应该使用
MediaElement.srcObject = MediaStream
相反