1
jifengg 2023-06-14 08:58:27 +08:00
不清楚具体原理,不过,你的 navigator.mediaDevices.getUserMedia 覆写 是在 video canplay 之后,是否这期间其他 js 代码已经调用 navigator.mediaDevices.getUserMedia 了呢?
|
2
NouveauNom OP @jifengg 把代码改为
<!DOCTYPE html> <html> <head> <title>摄像头实时预览</title> <style> #video-preview { width: 100%; height: auto; } </style> </head> <body> <video id="video-preview" autoplay></video> <video id="video-preview2" autoplay></video> <div id="container"></div> <button onclick="click2()"> click2</button> <script> // 获取视频流 let video; async function playVideo(url) { video = document.createElement("video"); video.setAttribute('id', 'video-mock'); video.setAttribute("src", url); // video.setAttribute("crossorigin", "anonymous"); // video.setAttribute("controls", ""); video.oncanplay = async () => { }; video.onplay = async () => { const stream = video.captureStream(); navigator.mediaDevices.getUserMedia = () => Promise.resolve(stream); }; videoCreated = true; } // 在页面中创建一个按钮,并绑定点击事件 const playButton = document.createElement('button'); playButton.textContent = '点击播放视频'; playButton.addEventListener('click', startVideoPlayback); // 将按钮添加到页面中的某个元素上 const container = document.getElementById('container'); container.appendChild(playButton); playVideo("test.mp4"); // 用户点击按钮后调用此函数 function startVideoPlayback() { video.play(); } function click2() { // 获取视频流 navigator.mediaDevices.getUserMedia({ video: true }) .then(function(stream2) { var videoElement = document.getElementById('video-preview2'); videoElement.srcObject = stream2; }) .catch(function(error) { console.error('访问摄像头失败:', error); }); } </script> </body> </html> 似乎 Chrome ,只是似乎可用,safari 直接报错了 |
3
NouveauNom OP 已经实现此功能,此贴结束。
|