Created
August 21, 2024 11:52
-
-
Save tblachowicz/3f3917a75e5387059d502fccdb6b0fe2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Record Video for 3 Seconds</title> | |
</head> | |
<body> | |
<h1>Record Video Example.</h1> | |
<!-- Button to start the recording --> | |
<button id="startRecordingButton">Start Recording</button> | |
<p>Recording stops automartically after 3 seconds</p> | |
<!-- Area where the recorded video will be displayed --> | |
<video id="recordedVideo" controls></video> | |
<script> | |
const startButton = document.getElementById('startRecordingButton'); | |
const recordedVideo = document.getElementById('recordedVideo'); | |
let mediaRecorder; | |
let recordedChunks = []; | |
startButton.addEventListener('click', () => { | |
// Request access to the camera | |
navigator.mediaDevices.getUserMedia({ video: true, audio: true }) | |
.then(stream => { | |
// Create a MediaRecorder instance to record the stream | |
mediaRecorder = new MediaRecorder(stream); | |
// Capture the recorded video chunks | |
mediaRecorder.ondataavailable = event => { | |
if (event.data.size > 0) { | |
recordedChunks.push(event.data); | |
} | |
}; | |
// Handle the stop event to process the recorded video | |
mediaRecorder.onstop = () => { | |
// Combine the recorded chunks into a Blob | |
const blob = new Blob(recordedChunks, { type: 'video/webm' }); | |
const url = URL.createObjectURL(blob); | |
// Set the Blob as the source of the video element | |
recordedVideo.src = url; | |
// Clear the recorded chunks for future recordings | |
recordedChunks = []; | |
}; | |
// Start recording the video | |
mediaRecorder.start(); | |
// Automatically stop recording after 3 seconds | |
setTimeout(() => { | |
mediaRecorder.stop(); | |
// Stop the stream to release the camera | |
stream.getTracks().forEach(track => track.stop()); | |
}, 3000); // Stop after 3000 milliseconds (3 seconds) | |
}) | |
.catch(error => { | |
console.error("Error accessing camera: ", error); | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment