<!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');
// 媒體設備約束
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();
// 當開始錄制時,將數據存儲在recordedChunks數組中
mediaRecorder.ondataavailable = event => {
console.log(event)
recordedChunks.push(event.data);
};
// 當錄制完成時,將錄制視頻呈現在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>