只是制作一个视频录制组件,你可以在以后重播,看看你是否喜欢它,如果不喜欢你就重新录制,最后它会将其存储在数据库中。我为此使用了react-webcam,其中包含一些我在网上找到的功能。
我有一个 handleDownload
函数,它使用我刚刚录制的 blob 设置视频标签源。最初,它在单击按钮时下载了视频文件,但我希望在停止录制后立即可以重播视频。理想情况下,我想使用相同的react-webcam组件,但不确定我能做到这一点,所以现在就可以了。
当我将函数设置为按钮的 onClick 监听器时,它可以工作,但是,当我在 handleStopCaptureClick
内部调用该函数时,它不起作用
所以我尝试实现一个 useEffect
,它会导致 handleDownload
在我们停止捕获后运行。 这也不起作用 - 想法?谢谢!
import React, {useEffect} from "react";
import Webcam from "react-webcam";
export const WebcamStreamCapture = () => {
const webcamRef = React.useRef(null);
const mediaRecorderRef = React.useRef(null);
const [capturing, setCapturing] = React.useState(false);
const [recordedChunks, setRecordedChunks] = React.useState([]);
const isInitialMount = React.useRef(true);
useEffect(() => {
if (isInitialMount.current) {
isInitialMount.current = false;
} else {
if (!capturing) {
console.log('running handleDownload')
handleDownload();
}
}
}, [capturing])
const handleStartCaptureClick = React.useCallback(() => {
setCapturing(true);
mediaRecorderRef.current = new MediaRecorder(webcamRef.current.stream, {
mimeType: "video/webm"
});
mediaRecorderRef.current.addEventListener(
"dataavailable",
handleDataAvailable
);
mediaRecorderRef.current.start();
}, [webcamRef, setCapturing, mediaRecorderRef]);
const handleDataAvailable = React.useCallback(
({ data }) => {
if (data.size > 0) {
setRecordedChunks((prev) => prev.concat(data));
}
},
[setRecordedChunks]
);
const handleStopCaptureClick = React.useCallback(() => {
mediaRecorderRef.current.stop();
setCapturing(false);
}, [mediaRecorderRef, webcamRef, setCapturing]);
const handleDownload = React.useCallback(() => {
if (recordedChunks.length) {
const blob = new Blob(recordedChunks, {
type: "video/webm"
});
const url = URL.createObjectURL(blob);
const video = document.getElementById("video-replay");
video.src = url
}
}, [recordedChunks]);
return (
<div className="d-flex flex-column align-items-center">
<Webcam audio={false} ref={webcamRef} height={400} width={500}/>
<video id="video-replay" height="400" width="500" controls></video>
{capturing ? (
<button className="btn btn-danger" onClick={handleStopCaptureClick}>Stop Capture</button>
) : (
<button className="btn btn-danger" onClick={handleStartCaptureClick}>Start Capture</button>
)}
{recordedChunks.length > 0 && (
<div>
<button onClick={handleDownload}>Download</button>
</div>
)}
</div>
);
};
可能的解决方案
所以我开始思考,如果这些 block 在 useEffect 期间也没有出现/工作,那一定意味着当在 handleStopCaptureClick
中捕获停止时,状态需要一段时间才能更新,包括我认为的 block 。通过将 useEffect 中的依赖项从“capturing”更改为“recordedChunks”,我成功地使视频在您停止录制后立即出现。
最佳答案
解决方案:通过将 useEffect 中的依赖项从“capturing”更改为“recordedChunks”,我成功地使视频在您停止录制后立即出现。
关于javascript - React-网络摄像头录制、重放、重新录制、存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67828731/