从视频流中获取数据 URL?

Utk*_*nos 3 javascript video stream webm webrtc

我有一个工作正常的视频(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);
Run Code Online (Sandbox Code Playgroud)

正如我所说,这有效。但是,控制台表示不URL.createObjectURL推荐将媒体流传递给,我应该使用 HTMLMediaElementsrcObject代替。

所以我把它改为:

a.href = URL.createObjectURL(video.srcObject);
Run Code Online (Sandbox Code Playgroud)

...虽然一切仍然有效,但我收到了同样的警告。

有谁知道如何在不使用这种已弃用的方式的情况下获取 URL 或 blob 数据?

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

Kai*_*ido 5

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

如果stream确实是 a MediaStream,那么浏览器甚至不应该知道它需要下载的大小,因此不知道何时停止下载(它是一个流)。

MediaRecorder#ondataavailable将公开一个事件,其data属性填充了录制的 MediaStream 的块。在这种情况下,您必须将这些块存储在数组中,然后通常在 MediaRecorder#onstop 事件中下载这些 Blob 块的串联。

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);
}
Run Code Online (Sandbox Code Playgroud)

URL.createObjectURL(MediaStream)用于<video>元素。但这也给浏览器关闭物理设备访问带来了一些困难,因为 BlobURL 的生命周期可能比当前文档更长。
因此,现在不推荐使用createObjectURLMediaStream 进行调用,而应该使用它MediaElement.srcObject = MediaStream