摄像头录制视频

49 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>摄像头录制</title>
</head>
<body>
  <video id="videoElement" width="400" height="300" autoplay></video>
  <button id="startButton">开始录制</button>
  <button id="stopButton">停止录制</button>

  <script>
    const videoElement = document.getElementById('videoElement');
    const startButton = document.getElementById('startButton');
    const stopButton = document.getElementById('stopButton');
    let mediaRecorder;
    let chunks = [];

    navigator.mediaDevices.getUserMedia({ video: true, audio: false })
      .then(function(stream) {
        videoElement.srcObject = stream;
        mediaRecorder = new MediaRecorder(stream);

        mediaRecorder.ondataavailable = function(e) {
          chunks.push(e.data);
        };

        mediaRecorder.onstop = function() {
          const blob = new Blob(chunks, { type: 'video/webm' });
          const videoUrl = URL.createObjectURL(blob);
          const downloadLink = document.createElement('a');
          downloadLink.href = videoUrl;
          downloadLink.download = 'recorded-video.webm';
          downloadLink.click();
          chunks = [];
        };
      })
      .catch(function(err) {
        console.log('访问摄像头失败:', err);
      });

    startButton.addEventListener('click', function() {
      mediaRecorder.start();
    });

    stopButton.addEventListener('click', function() {
      mediaRecorder.stop();
    });
  </script>
</body>
</html>