<!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>
网友评论