I already have getUserMedia working in my ReactJSX file. I'm new to ReactJSX, and i've viewed some stackoverflow posts related to this, but unfortunately many of the existing instructions include a line of code/function that is deprecated by webRTC.
However, I haven't been able to figure how to stop the web cam stream and microphone in React JSX , in particular. And since this language is quite new for me, can anyone help me?
This is the working code I have before the return()
tag in React JSX
navigator.mediaDevices.getUserMedia({
audio: true,
video: true
})
.then(stream => {
document.getElementById("startstream").srcObject = stream;
})
And this is the working code I have to display and enable the camera and microphone after the return()
tag in React JSX:
<video id="startstream" autoPlay />
Both of those code snippets work, and it allows the user to start the stream/start their microphone, but how do I start and stop the webcam/microphone using a button in ReactJSX? I've seen something similar online using another coding language, but if anyone code help me to get it to work with ReactJSX, that would be appreciated.
import React from "react";
import "./styles.css";
class WebRTCSample extends React.Component {
constructor(props) {
super(props);
this.state = { localStream: null };
}
componentDidMount() {}
startWebCam = () => {
const that = this;
navigator.mediaDevices
.getUserMedia({
audio: true,
video: true
})
.then((stream) => {
that.setState({ localStream: stream });
});
};
stopWebCam = () => {
this.state.localStream.getTracks().forEach((track) => {
track.stop();
});
};
render() {
return (
<div className="App">
{/* <h1>Hello GetUserMedia</h1> */}
{this.state.localStream && (
<video
autoPlay
ref={(video) => {
if (video) {
video.srcObject = this.state.localStream;
}
}}
// src={this.state.localStream}
/>
)}
<div className="startStopWebCam">
<button
className="WebCamButton"
onClick={this.startWebCam.bind(this)}
>
Start
</button>
<button className="WebCamButton" onClick={this.stopWebCam.bind(this)}>
Stop
</button>
</div>
</div>
);
}
}
export default WebRTCSample;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.