js 視頻錄制/錄像

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>攝像頭錄制視頻</title>
<style>
video {
width: 100%;
max-width: 500px;
height: auto;
}
</style>
</head>
<body>
<h1>攝像頭錄制視頻</h1>
<video id="video" autoplay></video>
<button id="startButton">開始錄制</button>
<button id="stopButton">停止錄制</button>
<video id="video1" autoplay></video>

<script type="text/javascript">
// 獲取頁面元素
const video = document.getElementById('video');
const video1 = document.getElementById('video1');
const startButton = document.getElementById('startButton');
const stopButton = document.getElementById('stopButton');
// 媒體設(shè)備約束
const constraints = {
video: true,
audio: false
};

// 定義全局變量
let mediaRecorder;
let mediaStreamTrack;
let recordedChunks = [];

function startrecord () {
// 獲取攝像頭流
navigator.mediaDevices.getUserMedia(constraints)
.then(stream => {
mediaStreamTrack = stream
video.srcObject = stream;
mediaRecorder = new MediaRecorder(stream);

    recordedChunks = [];
    mediaRecorder.start();



    // 當開始錄制時,將數(shù)據(jù)存儲在recordedChunks數(shù)組中
    mediaRecorder.ondataavailable = event => {
      console.log(event)
      recordedChunks.push(event.data);
    };

    // 當錄制完成時,將錄制視頻呈現(xiàn)在video元素中
    mediaRecorder.onstop = () => {
      const recordedBlob = new Blob(recordedChunks, { type: 'video/mp4' });
      var url = URL.createObjectURL(recordedBlob);
      console.log(url)
      video1.src = url
      video1.controls = true;

      // 下載
      var a = document.createElement("a");
      document.body.appendChild(a);
      a.style = "display: none";
      a.href = url;
      a.download = "test.mp4";
      a.click();
      // window.URL.revokeObjectURL(url);
    };


  })
  .catch(err => {
    console.error(`攝像頭流獲取失敗: ${err}`);
  });

}

// 當點擊“開始錄制”按鈕時,開始錄制
startButton.addEventListener('click', () => {
startrecord();

});

// 當點擊“停止錄制”按鈕時,停止錄制
stopButton.addEventListener('click', () => {
mediaRecorder.stop();
mediaStreamTrack.getVideoTracks().forEach(track => {
track.stop()
})
});

</script>

</body>
</html>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容