<!DOCTYPE html>
<html>
<head>
<title>WebRTC音视频录制演示</title>
</head>
<body>
<h1>WebRTC音视频录制演示</h1>
<video id="video" autoplay muted></video>
<button id="startButton">开始录制</button>
<button id="stopButton">停止录制</button>
<button id="downloadButton" disabled>下载录制文件</button>
<script>
const videoElement = document.getElementById('video');
const startButton = document.getElementById('startButton');
const stopButton = document.getElementById('stopButton');
const downloadButton = document.getElementById('downloadButton');
let mediaRecorder;
let recordedChunks = [];
async function setupMedia() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
videoElement.srcObject = stream;
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = handleDataAvailable;
mediaRecorder.onstop = handleStop;
startButton.disabled = false;
} catch (err) {
console.error('访问媒体设备时出错:', err);
}
}
function startRecording() {
recordedChunks = [];
mediaRecorder.start();
startButton.disabled = true;
stopButton.disabled = false;
}
function stopRecording() {
mediaRecorder.stop();
startButton.disabled = false;
stopButton.disabled = true;
}
function handleDataAvailable(event) {
recordedChunks.push(event.data);
}
function handleStop() {
const blob = new Blob(recordedChunks, { type: 'video/webm' });
const url = URL.createObjectURL(blob);
downloadButton.href = url;
downloadButton.download = 'recorded.webm';
downloadButton.disabled = false;
}
setupMedia();
startButton.addEventListener('click', startRecording);
stopButton.addEventListener('click', stopRecording);
downloadButton.addEventListener('click', () => {
if (recordedChunks.length === 0) {
alert('没有可用的录制数据。');
return;
}
const blob = new Blob(recordedChunks, { type: 'video/webm' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'recorded.webm';
a.click();
});
</script>
</body>
</html>