HTML5视频元素请求永远保持挂起(在移动的中的Chrome上),当切换到前置摄像头时

093gszye  于 2023-09-28  发布在  Go
关注(0)|答案(2)|浏览(119)

我正在开发一个应用程序,用户可以使用前置/罕见的相机捕捉照片。它工作完美,但当切换到相机前/罕见**var playPromise = videoStream.play()**是在挂起状态。有时承诺得到解决,相机有时不工作。
此问题仅发生在Chrome浏览器中,而不是Mozilla和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)
    }
ldxq2e6h

ldxq2e6h1#

在这里,我为你起草了一段代码,这比你试图做的更简单,更小的方法。我只是从video元素中获取流并将其绘制到画布上。图像可以通过右键单击下载。注意:示例在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>

如果你愿意,你也可以根据自己的需要进行一些编辑,比如:
1.选择要使用的相机
1.隐藏视频流
1.添加一个更简单的方法来下载您的设备上的照片
1.你也可以添加一个功能,直接上传照片到服务器,如果你有一个

lvjbypge

lvjbypge2#

检查视频分辨率是否超过4k(3840x2160)。如果为真,请尝试缩小。

相关问题