Created
August 19, 2023 17:20
-
-
Save Clever-Shivanshu/3474a9d8829c1ea5d31c5d74dd8c2a41 to your computer and use it in GitHub Desktop.
screen record
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
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