Interface : 4 WebRTC and CameraTab.js - 17chuchu/AutomaticBicycleInterface GitHub Wiki
This page will be WebRTC and CameraTab.js.
WebRTC is a new way to efficiently create data streams by using peer to peer connection. This web-application use SimeplWebRTC version of WebRTC.
WebRTC's part of this web-application is located in src/component/CameraTab.js
.
This code block will initialize WebRTC on your web-application.
componentDidMount() {
this.webrtc = new SimpleWebRTC({
url: 'http://141.44.17.141:8080'. // Connect to this ip at this port
});
this.webrtc.on('videoAdded', this.addVideo); // Add an event listener when a new video stream is added.
this.webrtc.on('videoRemoved', this.removeVideo); // Add an event listener when a existed video is removed.
console.log("webrtc component mounted");
}
To join a room, execute this line. When you publish a video stream to a room, other clients in this room will know about it and can choose to receive or deny that video stream.
this.webrtc.joinRoom(info.pack.token);
To leave a room, execute this line. When someone leaves the room, you will be notified and that video stream will be removed.
this.webrtc.leaveRoom();
When a new video stream is added, you can present it by adding it to a React component.
Firstly we need to have a div
component like this.
<div
ref = "remotes" >
</div>
Then back to the event when we are going to initialize the video. We have a callback function called addVideo, to present the video stream to the user. This is that function.
addVideo = async (video, peer) => { // video.srcObject is the video stream that is being sent.
console.log('video added', peer);
var remotes = ReactDOM.findDOMNode(this.refs.remotes); // Find the div component.
console.log(video);
if (remotes) {
var container = document.createElement('div');
container.style.transform = 'rotateY(-180deg)' // I flip the video horizontally.
container.className = 'videoContainer';
container.id = 'container_' + this.webrtc.getDomId(peer);
container.appendChild(video);
// suppress contextmenu
video.oncontextmenu = function() {
return false;
};
video.width = 800
video.muted = true // You can also mute the video stream.
console.log(container);
remotes.appendChild(container); // Add the video to the div container so it can be presented to you.
}
this.webrtc.mute()
}
This is the callback function from when we want to initialize the video.
removeVideo = async(video, peer) => {
console.log('video removed ', peer);
var remotes = ReactDOM.findDOMNode(this.refs.remotes);
var el = document.getElementById(peer ? 'container_' + this.webrtc.getDomId(peer) : 'localScreenContainer');
if (remotes && el) {
remotes.removeChild(el);
}
}