|
1 | | -import { useState, useRef } from 'react'; |
| 1 | +import { useState, useRef, useEffect } from 'react'; |
2 | 2 |
|
3 | 3 | function useUserMedia(constraints, videoRef) { |
4 | 4 | const [stream, setStream] = useState(); |
@@ -47,3 +47,80 @@ export function useMediaRecorder({ constraints, onStop, videoRef }) { |
47 | 47 |
|
48 | 48 | return [start, stop]; |
49 | 49 | } |
| 50 | + |
| 51 | +export function useNewMediaRecorder({ constraints, videoRef, onStop }) { |
| 52 | + const [stream, setStream] = useState(); |
| 53 | + const [isStreaming, setIsStreaming] = useState(false); |
| 54 | + const [recorder, setRecorder] = useState(); |
| 55 | + const [recordingData, setRecordingData] = useState(null); |
| 56 | + const chunks = useRef([]); |
| 57 | + |
| 58 | + async function startCameraAndMic() { |
| 59 | + if (isStreaming) return; |
| 60 | + try { |
| 61 | + const _stream = await navigator.mediaDevices.getUserMedia(constraints); |
| 62 | + setStream(_stream); |
| 63 | + setIsStreaming(true); |
| 64 | + if (videoRef.current) { |
| 65 | + videoRef.current.srcObject = _stream; |
| 66 | + } |
| 67 | + } catch (error) { |
| 68 | + console.error('Error starting camera and mic:', error); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + async function startRecording() { |
| 73 | + if (!isStreaming) { |
| 74 | + console.error('Camera and mic must be on to start recording.'); |
| 75 | + return; |
| 76 | + } |
| 77 | + |
| 78 | + chunks.current = []; |
| 79 | + const _recorder = new MediaRecorder(stream); |
| 80 | + _recorder.start(); |
| 81 | + setRecorder(_recorder); |
| 82 | + |
| 83 | + _recorder.addEventListener('dataavailable', (event) => { |
| 84 | + chunks.current.push(event.data); |
| 85 | + }); |
| 86 | + |
| 87 | + _recorder.addEventListener('stop', () => { |
| 88 | + setRecordingData(new Blob(chunks.current, { type: 'video/mp4' })); |
| 89 | + onStop && onStop(chunks.current); |
| 90 | + }); |
| 91 | + } |
| 92 | + |
| 93 | + async function stopRecording() { |
| 94 | + if (recorder && recorder.state === 'recording') { |
| 95 | + recorder.stop(); |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + function getRecording() { |
| 100 | + return recordingData; |
| 101 | + } |
| 102 | + |
| 103 | + function deleteRecording() { |
| 104 | + setRecordingData(null); |
| 105 | + chunks.current = []; |
| 106 | + } |
| 107 | + |
| 108 | + function stopCameraAndMic() { |
| 109 | + if (stream) { |
| 110 | + stream.getTracks().forEach((track) => track.stop()); |
| 111 | + setStream(null); |
| 112 | + setIsStreaming(false); |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + useEffect(() => () => stopCameraAndMic(), []); |
| 117 | + |
| 118 | + return { |
| 119 | + startCameraAndMic, |
| 120 | + startRecording, |
| 121 | + stopRecording, |
| 122 | + getRecording, |
| 123 | + deleteRecording, |
| 124 | + stopCameraAndMic, |
| 125 | + }; |
| 126 | +} |
0 commit comments