gpt4 book ai didi

javascript - 从视频流中获取数据 URL?

转载 作者:行者123 更新时间:2023-11-29 19:02:43 25 4
gpt4 key购买 nike

我有一个工作正常的视频 (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 数据?

我也曾尝试从视频元素中读取 srccurrentSrc 属性,但在涉及流的地方它们返回为空。

最佳答案

我真的很惊讶你的代码竟然能工作......

如果stream真的是MediaStream ,那么浏览器甚至不知道它必须下载多大的文件,因此不知道何时停止下载(它是一个流)。

MediaRecorder#ondataavailable将公开一个带有 data 的事件属性填充了一 block 记录的 MediaStream。在这种情况下,您必须将这些 block 存储在一个数组中,然后您将下载这些 Blob block 的串联,通常是在 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使用 MediaStream,应该使用 MediaElement.srcObject = MediaStream相反。

关于javascript - 从视频流中获取数据 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45691394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com