javascript - HTML5 MediaRecorder 实现摄像功能(详细示例代码)
// 获取页面中的视频元素和按钮
const videoElement = document.querySelector('video');
const startRecordingButton = document.getElementById('start-recording');
const stopRecordingButton = document.getElementById('stop-recording');
let mediaRecorder;
let recordedBlobs;
// 开始录制的函数
function startRecording() {
recordedBlobs = [];
const stream = videoElement.srcObject;
mediaRecorder = new MediaRecorder(stream, { mimeType: 'video/webm' });
mediaRecorder.ondataavailable = event => recordedBlobs.push(event.data);
mediaRecorder.start();
console.log('Recording started');
}
// 停止录制的函数
function stopRecording() {
mediaRecorder.stop();
console.log('Recording stopped');
}
// 处理录制结束的函数
mediaRecorder.onstop = e => {
const superBuffer = new Blob(recordedBlobs, { type: 'video/webm' });
// 创建一个下载链接
const url = URL.createObjectURL(superBuffer);
const a = document.createElement('a');
a.href = url;
a.download = 'recording.webm';
a.click();
// 清理资源
window.URL.revokeObjectURL(url);
};
// 监听按钮点击事件
startRecordingButton.addEventListener('click', startRecording);
stopRecordingButton.addEventListener('click', stopRecording);
这段代码实现了使用HTML5 MediaRecorder API进行视频录制的基本功能。首先,获取页面中的视频元素和开始/停止按钮。然后定义了开始录制和停止录制的函数,并在录制结束时处理下载录制内容的逻辑。最后,为按钮绑定点击事件监听器。
评论已关闭