videoRecorder.js
1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const recorderContainer = document.getElementById("jsRecordContainer");
const recordBtn = document.getElementById("jsRecordBtn");
const videoPreview = document.getElementById("jsVideoPreview");
// media devices navigator mdn -> video API
let streamObject;
let videoRecorder;
const handleVideoData = (event) => {
const { data: videoFile } = event;
const link = document.createElement("a");
link.href = URL.createObjectURL(videoFile);
link.download = "recorded.webm";
document.body.appendChild(link);
link.click();
};
const stopRecording = () => {
videoRecorder.stop();
recordBtn.removeEventListener("click", stopRecording);
recordBtn.addEventListener("click", getVideo);
recordBtn.innerHTML = "Start recording";
};
const startRecording = () => {
videoRecorder = new MediaRecorder(streamObject);
videoRecorder.start();
videoRecorder.addEventListener("dataavailable", handleVideoData);
recordBtn.addEventListener("click", stopRecording);
};
const getVideo = async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({
audio: true,
video: { width: 1280, height: 720 },
});
videoPreview.srcObject = stream;
videoPreview.play();
videoPreview.muted = true;
recordBtn.innerHTML = "Stop recording.";
streamObject = stream;
startRecording();
} catch (error) {
recordBtn.innerHTML = "Sorry, You can't recording.";
} finally {
recordBtn.removeEventListener("click", getVideo);
}
};
function init() {
recordBtn.addEventListener("click", getVideo);
}
if (recorderContainer) {
init();
}