I'm trying to write a method to toggle camera for turn on/off the camera.
Call Peer
const callPeer = (myPeer, peerId, myVideoStream, addToCalls = true) => {
const call = myPeer.call(peerId, myVideoStream);
if (addToCalls) {
let existingCall = myPeer.calls.find((existingCall) => existingCall.peer == peerId);
if (existingCall)
myPeer.calls.splice(myPeer.calls.indexOf(existingCall), 1);
myPeer.calls.push(call);
call.on('stream', peerVideoStream => {
let userVideoElement = $("video[data-peer='" + peerId + "']")[0];
userVideoElement.srcObject = peerVideoStream;
});
}
}
Answer Call
const answerCall = (call, addToCalls = true) => {
call.answer(myVideoStream);
if (addToCalls) {
let existingCall = myPeer.calls.find((existingCall) => existingCall.peer == call.peer);
if (existingCall)
myPeer.calls.splice(myPeer.calls.indexOf(existingCall), 1);
myPeer.calls.push(call);
}
call.on('stream', userVideoStream => {
let userVideoElement = $("video[data-peer='" + call.peer + "']")[0];
userVideoElement.srcObject = userVideoStream;
});
}
Toggle Camera
const toggleCamera = async (isOpened, peerId, isMuted) => {
let oldStream = myVideoStream;
myVideoStream = await navigator.mediaDevices.getUserMedia({
video: !isOpened,
audio: true
});
myPeer.calls.forEach((call) => {
call.peerConnection.removeStream(oldStream);
call.peerConnection.addStream(myVideoStream);
});
oldStream.getTracks().forEach((track) => {
track.stop();
});
let myVideoElement = document.querySelector("video[data-peer='" + peerId + "']");
myVideoElement.srcObject = myVideoStream;
myVideoElement.muted = true;
if (isOpened)
$("#video").removeClass("bg-primary").attr("data-video", "closed");
else
$("#video").addClass("bg-primary").attr("data-video", "opened");
ws.send(JSON.stringify({
type: isOpened ? "video-off" : "video-on"
}));
if (isMuted)
myVideoStream.getAudioTracks()[0].enabled = false;
};
When I print the localstream at peer connection, it seems like localstream is switched but when I print the remote stream from other client, Its not changing. So stream event is not runnig.
I also tried to write a event for onaddstream but it also didn't work.