forked from yondonfu/comfystream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebcam.tsx
65 lines (54 loc) · 1.55 KB
/
webcam.tsx
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
import React, { useEffect, useRef, useCallback } from "react";
interface WebcamProps {
onStreamReady: (stream: MediaStream) => void;
}
export function Webcam({ onStreamReady }: WebcamProps) {
const videoRef = useRef<HTMLVideoElement>(null);
const streamRef = useRef<MediaStream | null>(null);
const captureStream = useCallback(() => {
if (videoRef.current) {
// cast to any because captureStream() not recognized
const video = videoRef.current as any;
const stream = video.captureStream(30);
streamRef.current = stream;
onStreamReady(stream);
}
}, [onStreamReady]);
useEffect(() => {
const startWebcam = async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: {
width: { exact: 512 },
height: { exact: 512 },
},
audio: {
noiseSuppression: true,
echoCancellation: true,
sampleRate: 16000,
sampleSize: 16,
},
});
if (videoRef.current) videoRef.current.srcObject = stream;
captureStream();
} catch (err) {
console.error(err);
}
};
startWebcam();
return () => {
if (
videoRef.current &&
videoRef.current.srcObject instanceof MediaStream
) {
const tracks = videoRef.current.srcObject.getTracks();
tracks.forEach((track: MediaStreamTrack) => track.stop());
}
};
}, []);
return (
<div>
<video ref={videoRef} autoPlay playsInline />
</div>
);
}