File size: 1,466 Bytes
babeaf6 |
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 |
/**
* src/hooks/useMediaRecorder.js
* Initialize media recorder. Start and stop recording.
*
* created by Lynchee on 7/16/23
*/
import { useState, useRef } from 'react';
const useMediaRecorder = (onDataAvailable, onStop) => {
const [isRecording, setIsRecording] = useState(false);
const mediaRecorder = useRef(null);
// initialize media recorder
const connectMicrophone = (deviceId) => {
if (mediaRecorder.current) return;
navigator.mediaDevices.getUserMedia({
audio: { deviceId: deviceId ? {exact: deviceId} : undefined, echoCancellation: true }
})
.then((stream) => {
mediaRecorder.current = new MediaRecorder(stream);
mediaRecorder.current.ondataavailable = onDataAvailable;
mediaRecorder.current.onstop = onStop;
})
.catch(function(err) {
console.log('An error occurred: ' + err);
});
};
const startRecording = () => {
console.log("start recording");
if (!mediaRecorder.current) return;
mediaRecorder.current.start();
setIsRecording(true);
}
const stopRecording = () => {
console.log("stop recording");
if (!mediaRecorder.current) return;
mediaRecorder.current.stop();
setIsRecording(false);
};
const closeMediaRecorder = () => {
stopRecording();
mediaRecorder.current = null;
};
return { isRecording, setIsRecording, connectMicrophone, startRecording, stopRecording, closeMediaRecorder };
};
export default useMediaRecorder;
|