javascript - 切换前置罕见摄像头时,HTML5 视频元素请求永远保持挂起状态(在移动设备上的 chrome 上)
问题描述
我正在开发一个应用程序,用户可以在其中使用前置/稀有相机拍摄照片。它工作得很好,但是当切换相机前端/罕见的var playPromise = videoStream.play()时,它处于挂起状态。有时承诺得到解决,相机工作有时不。
此问题仅在 chrome 浏览器中出现,而不在 mozila 和 firefox 中出现
try { stopWebCam(); // stop media stream when toggle over camera stream = await navigator.mediaDevices.getUserMedia({video: true}); /* use the stream */ let videoStream = document.getElementById('captureCandidateId'); videoStream.srcObject = stream; // videoStream.play(); var playPromise = videoStream.play(); if (playPromise !== undefined) { playPromise.then(_ => { // Automatic playback started! // Show playing UI. }) .catch(error => { // Auto-play was prevented // Show paused UI. }); } }; } catch(err) { /* handle the error */ console.log(err.name + ": " + err.message); }
let stopWebCam = function (pictureType) { setTimeout(()=>{ let videoStream = document.getElementById('captureCandidateId'); const stream = videoStream.srcObject; if (stream && stream.getTracks) { const tracks = stream.getTracks(); tracks.forEach(function(track) { track.stop(); }); } videoStream.srcObject = null; }, 0) }
解决方案
在这里,我为您起草了一段代码,这比您尝试做的更简单、更小。我只是从视频元素中获取流并将其绘制到画布上。图片可以右键下载。注意:示例在 StackOverflow 中不起作用
<video id="player" controls autoplay></video>
<button id="capture">Capture</button>
<canvas id="canvas" width=320 height=240></canvas>
<script>
const player = document.getElementById('player');
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const captureButton = document.getElementById('capture');
const constraints = {
video: true,
};
captureButton.addEventListener('click', () => {
// Draw the video frame to the canvas.
context.drawImage(player, 0, 0, canvas.width, canvas.height);
});
// Attach the video stream to the video element and autoplay.
navigator.mediaDevices.getUserMedia(constraints)
.then((stream) => {
player.srcObject = stream;
});
</script>
如果需要,您还可以根据需要进行一些编辑,例如:
- 选择要使用的相机
- 隐藏视频流
- 添加更简单的方法以在您的设备上下载照片
- 您还可以添加一项功能,将照片直接上传到服务器(如果您有的话)
推荐阅读
- c# - 覆盖 WPF 中的工具提示
- android - (可变)在 UI 上未观察到 LiveData
- c# - Azure 函数异常 - 将日志写入表存储时出错:Microsoft.Azure.Cosmos.Table.StorageException
- javascript - 如何使文本自动出现在搜索栏中?
- python - ModuleNotFoundError: No module named 'PIL' ,在处理上述异常的过程中,又发生了一个异常:
- c - 检查不相关进程的退出代码
- reactjs - Next.js 和 next.config.js 中的多个 module.exports 选项
- sql - SQL。根据预期小时数按月拆分数据
- r - 如何在最小化绘图文件大小的同时存储乘客上下火车的位置?
- php - Pestphp 错误:调用未定义的函数 mock()