问题
I'm a a beginner in web development and I’m working on a video chat app built with create-react-app
. I’m using recordRTC
library for record and stream from users’s webcam and microphone.
When I stop recording, I also would like to close the webcam.
import React, { Component } from "react";
import RecordRTC from "recordrtc";
const captureUserMedia = callback => {
const params = { audio: true, video: true };
navigator.mediaDevices
.getUserMedia(params)
.then(callback)
.catch((error) => {
console.error(JSON.stringify(error));
});
};
export default class Recorder extends Component {
constructor(props) {
super(props);
this.recordVideo = null;
this.videoRef = React.createRef();
}
componentDidMount = () => {
captureUserMedia(stream => (this.videoRef.current.srcObject = stream));
};
startRecord = () => {
captureUserMedia(stream => {
this.recordVideo = RecordRTC(stream, { type: "video" });
this.recordVideo.startRecording();
});
};
stopRecord = () => {
this.recordVideo.stopRecording();
this.videoRef.current.srcObject.getTracks().forEach((track) => {
track.stop();
});
};
render() {
return (
<div>
<video ref={this.videoRef} autoPlay muted />
<div>
<button onClick={this.startRecord}>START</button>
<button onClick={this.stopRecord}>STOP</button>
</div>
</div>
);
}
}
I found here a related post where I found this:
stream.getTracks().forEach((track) => {
track.stop()
})
This stop the stream but the red circle is still present on the navigator tab (chrome) and the webcam's light is still lightning.
How can I do to turn off the webcam ?
The only way i found is to force a reload but I don't really wanna do this ...
If someone have an idea, please let me know.
Thanks for your reply :)
回答1:
I found what I did wrong !
I called two times getUserMedia()
method instead of one only (with captureUserMedia function).
You can try with the code below it will be ok !!!
...
componentDidMount = () => {
captureUserMedia((stream) => {
this.videoRef.current.srcObject = stream;
this.recordVideo = RecordRTC(stream, { type: "video" });
});
};
startRecord = () => {
this.recordVideo.startRecording();
};
stopRecord = () => {
this.recordVideo.stopRecording();
this.videoRef.current.srcObject.getTracks().forEach((track) => {
track.stop();
});
};
...
来源:https://stackoverflow.com/questions/52905393/closing-webcam-without-reloading