是否可以从具有跨源数据的元素中捕获?

2024-03-31

我在 webRTC 文档中找到了这个简单的脚本,我尝试运行它,但似乎我遗漏了一些东西

const leftVideo = document.getElementById('leftVideo');
const rightVideo = document.getElementById('rightVideo');

leftVideo.addEventListener('canplay', () => {
const stream = leftVideo.captureStream();
rightVideo.srcObject = stream;
});

当我检查流捕获时,我收到此错误 未捕获的 DOMException:无法在“HTMLMediaElement”上执行“captureStream”:无法从具有跨源数据的元素捕获 在 HTMLVideoElement.leftVideo.addEventListener 这是我的index.html

<video id="leftVideo" playsinline controls loop muted>
    <source src="test1.webm" type="video/webm"/>
    <p>This browser does not support the video element.</p>
</video>

<video id="rightVideo" playsinline autoplay></video>

  1. 您可以按照此链接所示设置 crossOrigin 例子:
<video crossOrigin="anonymous" src="https://cdn.myapp.com:81/video.mp4"></video>

您想确保链接使用 https

参考:https://stackoverflow.com/a/35245146/8689969 https://stackoverflow.com/a/35245146/8689969

  1. 或者您可以使用 fetch 创建一个可读流,跟踪此链接上的文档:https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream这将为您提供 blob url,这应该有助于解决该问题: 例子:
// Fetch the original image
    fetch(video.filePath,  {
      mode: 'cors',
      headers: {
        'Access-Control-Allow-Origin':'*'
      }
    })
    // Retrieve its body as ReadableStream
    .then(response => {
      const reader = response.body.getReader();

      return new ReadableStream({
        start(controller) {
          return pump();
          function pump() {
            return reader.read().then(({ done, value }) => {
              // When no more data needs to be consumed, close the stream
              if (done) {
                  controller.close();
                  return;
              }
              // Enqueue the next data chunk into our target stream
              controller.enqueue(value);
              return pump();
            });
          }
        }  
      })
    })
    .then(stream => new Response(stream))
    .then(response => response.blob())
    .then(blob => URL.createObjectURL(blob))
    .then((url) => {
      // gives the blob url which solves cors error in reading stream(using captureStream() func)

      console.log(url);

      // do your thing
    })
    .catch(err => console.error(err));
  • 祝你好运...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否可以从具有跨源数据的元素中捕获? 的相关文章

随机推荐