Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Clever-Shivanshu/3474a9d8829c1ea5d31c5d74dd8c2a41 to your computer and use it in GitHub Desktop.
Save Clever-Shivanshu/3474a9d8829c1ea5d31c5d74dd8c2a41 to your computer and use it in GitHub Desktop.
screen record
import { useState, useEffect, useRef } from 'react';
const ScreenRecorder = () => {
const [stream, setStream] = useState(null);
const [recording, setRecording] = useState(false);
const mediaRecorderRef = useRef(null);
const chunksRef = useRef([]);
const startRecording = async () => {
try {
const stream = await navigator.mediaDevices.getDisplayMedia({ video: true });
setStream(stream);
const mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = event => {
if (event.data.size > 0) {
chunksRef.current.push(event.data);
}
};
mediaRecorder.onstop = () => {
const blob = new Blob(chunksRef.current, { type: 'video/webm' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'recorded-screen.webm';
a.click();
chunksRef.current = [];
};
mediaRecorderRef.current = mediaRecorder;
mediaRecorder.start();
setRecording(true);
} catch (error) {
console.error('Error starting recording:', error);
}
};
const stopRecording = () => {
if (mediaRecorderRef.current && stream) {
mediaRecorderRef.current.stop();
stream.getTracks().forEach(track => track.stop());
setStream(null);
setRecording(false);
}
};
useEffect(() => {
return () => {
if (stream) {
stream.getTracks().forEach(track => track.stop());
}
};
}, [stream]);
return (
<div>
<button onClick={recording ? stopRecording : startRecording}>
{recording ? 'Stop Recording' : 'Start Recording'}
</button>
</div>
);
};
export default ScreenRecorder;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment