我有一个工作正常的视频(webm)捕获脚本。它录制视频然后提供下载。代码的相关部分是这样的:
stopBtn.addEventListener('click', function() {
recorder.ondataavailable = e => {
ul.style.display = 'block';
var a = document.createElement('a'),
li = document.createElement('li');
a.download = ['video_', (new Date() + '').slice(4, 28), '.'+vid_format].join('');
a.textContent = a.download;
a.href = URL.createObjectURL(stream); //<-- deprecated usage?
li.appendChild(a);
ul.appendChild(li);
};
recorder.stop();
startBtn.removeAttribute('disabled');
stopBtn.disabled = true;
}, false);
正如我所说,这有效。但是,控制台表示不推荐将媒体流传递到
URL.createObjectURL
,我应该使用 HTMLMediaElement srcObject
。
所以我把它改为:
a.href = URL.createObjectURL(video.srcObject);
...虽然一切仍然有效,但我收到了相同的警告。
有谁知道如何在不使用这种已弃用的方式的情况下获取 URL 或 blob 数据?
我还尝试从视频元素中读取
src
和 currentSrc
属性,但在涉及流的地方它们返回为空。
我真的很惊讶你的代码居然还能工作......
如果
stream
确实是 MediaStream
,那么浏览器甚至不应该知道它需要下载的大小,因此不知道何时停止下载(它是一个流)。
MediaRecorder#ondataavailable
将公开一个带有 data
属性的事件,其中填充了录制的 MediaStream 块。在这种情况下,您必须将这些块存储在数组中,然后您将下载这些 Blob 块的串联,通常在 MediaRecorder#onstop 事件中。
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>
元素。但这也导致浏览器关闭物理设备访问遇到一些困难,因为 BlobURL 的生命周期可能比当前文档更长。createObjectURL
,而应该使用 MediaElement.srcObject = MediaStream
来代替。
video.srcObject=stream
var canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0)
var du = canvas.toDataURL()