<!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 downloadButton = document.querySelector("#download");
// 媒体设备约束
const constraints = {
video: true,
audio: false
};
// 定义全局变量
let mediaRecorder;
let recordedChunks = [];
// 获取摄像头流
navigator.mediaDevices.getUserMedia(constraints)
.then(stream => {
video.srcObject = stream;
mediaRecorder = new MediaRecorder(stream);
// 当开始录制时,将数据存储在recordedChunks数组中
mediaRecorder.ondataavailable = event => {
recordedChunks.push(event.data);
};
// 当录制完成时,将录制视频呈现在video元素中
mediaRecorder.onstop = () => {
const recordedBlob = new Blob(recordedChunks, { type: 'video/webm' });
video1.src = URL.createObjectURL(recordedBlob);
video1.controls = true;
};
})
.catch(err => {
console.error(`摄像头流获取失败: ${err}`);
});
// 当点击“开始录制”按钮时,开始录制
startButton.addEventListener('click', () => {
recordedChunks = [];
mediaRecorder.start();
});
// 当点击“停止录制”按钮时,停止录制
stopButton.addEventListener('click', () => {
mediaRecorder.stop();
});
</script>
</body>
</html>
js调用摄像头录像
于 2023-03-26 00:19:06 首次发布
该代码示例展示如何利用HTML5和JavaScript的MediaRecorderAPI从用户摄像头捕获视频流并进行录制,当用户点击开始和停止按钮时,可以开始和结束录制。录制的视频片段会存储在recordedChunks数组中,并在停止录制后合并成一个Blob对象,显示在video元素上。
摘要由CSDN通过智能技术生成