-
Notifications
You must be signed in to change notification settings - Fork 365
Expand file tree
/
Copy pathuseMediaRecorder.js
More file actions
164 lines (136 loc) · 4.3 KB
/
useMediaRecorder.js
File metadata and controls
164 lines (136 loc) · 4.3 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import { useState, useRef, useEffect } from 'react';
function useUserMedia(constraints, videoRef) {
const [stream, setStream] = useState();
async function getStream(refresh = false) {
if (stream && !refresh) {
return stream;
}
const _stream = await navigator.mediaDevices.getUserMedia(constraints);
setStream(_stream);
// Optionally, set the stream as the srcObject of the video element
if (videoRef.current) {
videoRef.current.srcObject = _stream;
}
return _stream;
}
return { stream, getStream };
}
export function useMediaRecorder({ constraints, onStop, videoRef }) {
const [recorder, setRecorder] = useState();
const { getStream } = useUserMedia(constraints, videoRef);
const chunks = useRef([]);
function getPreferredAudioMimeType() {
if (typeof MediaRecorder === 'undefined' || !MediaRecorder.isTypeSupported) {
return '';
}
const candidates = [
'audio/mpeg',
'audio/webm;codecs=opus',
'audio/ogg;codecs=opus',
'audio/webm',
'audio/ogg',
];
return candidates.find((type) => MediaRecorder.isTypeSupported(type)) || '';
}
async function start() {
const stream = await getStream(constraints, true);
chunks.current = [];
const shouldUseAudioMimeType = constraints?.audio && !constraints?.video;
const preferredMimeType = shouldUseAudioMimeType
? getPreferredAudioMimeType()
: '';
const _recorder = preferredMimeType
? new MediaRecorder(stream, { mimeType: preferredMimeType })
: new MediaRecorder(stream);
const handleDataAvailable = (event) => {
chunks.current.push(event.data);
};
const handleStop = () => {
onStop && onStop(chunks.current);
_recorder.removeEventListener('dataavailable', handleDataAvailable);
_recorder.removeEventListener('stop', handleStop);
};
_recorder.addEventListener('dataavailable', handleDataAvailable);
_recorder.addEventListener('stop', handleStop);
_recorder.start();
setRecorder(_recorder);
}
async function stop() {
if (recorder) {
if (recorder.state !== 'inactive') {
recorder.stop();
}
(await getStream()).getTracks().forEach((track) => track.stop());
}
}
return [start, stop];
}
export function useNewMediaRecorder({ constraints, videoRef, onStop }) {
const [stream, setStream] = useState();
const [isStreaming, setIsStreaming] = useState(false);
const [recorder, setRecorder] = useState();
const [recordingData, setRecordingData] = useState(null);
const chunks = useRef([]);
async function startCameraAndMic() {
if (isStreaming) return;
try {
const _stream = await navigator.mediaDevices.getUserMedia(constraints);
setStream(_stream);
setIsStreaming(true);
if (videoRef.current) {
videoRef.current.srcObject = _stream;
}
} catch (error) {
console.error('Error starting camera and mic:', error);
}
}
async function startRecording() {
if (!isStreaming) {
console.error('Camera and mic must be on to start recording.');
return;
}
chunks.current = [];
const _recorder = new MediaRecorder(stream);
const handleDataAvailable = (event) => {
chunks.current.push(event.data);
};
const handleStop = () => {
setRecordingData(new Blob(chunks.current, { type: 'video/mp4' }));
onStop && onStop(chunks.current);
_recorder.removeEventListener('dataavailable', handleDataAvailable);
_recorder.removeEventListener('stop', handleStop);
};
_recorder.addEventListener('dataavailable', handleDataAvailable);
_recorder.addEventListener('stop', handleStop);
_recorder.start();
setRecorder(_recorder);
}
async function stopRecording() {
if (recorder && recorder.state === 'recording') {
recorder.stop();
}
}
function getRecording() {
return recordingData;
}
function deleteRecording() {
setRecordingData(null);
chunks.current = [];
}
function stopCameraAndMic() {
if (stream) {
stream.getTracks().forEach((track) => track.stop());
setStream(null);
setIsStreaming(false);
}
}
useEffect(() => () => stopCameraAndMic(), []);
return {
startCameraAndMic,
startRecording,
stopRecording,
getRecording,
deleteRecording,
stopCameraAndMic,
};
}