大大大白鹅

js 视频录制

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button onclick="startRecording()">开始录像</button>
<button onclick="stopRecording()">结束录像</button>
<!-- <button onclick="startRecording()">下载录像</button> -->
</body>
<script>
let mediaStream;
let mediaRecorder;
let recordedChunks = [];

const startRecording = async () => {
try {
mediaStream = await navigator.mediaDevices.getDisplayMedia({
video: true,
audio: true
});

mediaRecorder = new MediaRecorder(mediaStream, {
mimeType: 'video/webm; codecs=vp9'
});
mediaRecorder.ondataavailable = handleDataAvailable;
mediaRecorder.start();
} catch (error) {
console.error("Error starting recording:", error);
}
};

const stopRecording = () => {
if (mediaRecorder && mediaRecorder.state !== "inactive") {
mediaRecorder.stop();
let list=mediaStream.getTracks()
list.forEach(track => {
track.stop()
});
setTimeout(()=>{
downloadRecording()
},1000)
}
};

const handleDataAvailable = (event) => {
if (event.data.size > 0) {
recordedChunks.push(event.data);
}
};

const downloadRecording = () => {
const blob = new Blob(recordedChunks, {
type: "video/mp4"
});
const url = URL.createObjectURL(blob);

const downloadLink = document.createElement("a");
downloadLink.href = url;
downloadLink.download = "recording.mp4";
downloadLink.click();

URL.revokeObjectURL(url);
};
</script>
</html>

posted on 2023-12-20 14:02  大大大白鹅  阅读(74)  评论(0编辑  收藏  举报

导航