const video = document.querySelector('video');
let client = {};
var stream;
navigator.mediaDevices.getUserMedia({ video: true, audio: true }, function (stream) {
stream = stream;
}, function () { })
.then(stream => {
connection.invoke('NewVideoClient');
video.srcObject = stream
video.play();
function InitPeer(type) {
var peer = new SimplePeer({
initiator: (type == 'init') ? true : false,
stream: stream,
trickle: false
});
peer.on('stream', function (stream) {
CreateVideo(stream);
});
peer.on('connect', () => {
console.log('CONNECT');
alert('CONNECT');
});
//peer.on('close', function () {
// document.getElementById('peerVideo').remove();
// peer.destroy();
//});
return peer;
}
// for peer type init
function CreatePeer() {
alert("Enter in to CreatePeer");
client.gotAnswer = false;
let peer = InitPeer('init');
// let data = null;
peer.on('signal', function (data) {
if (!client.gotAnswer) {
connection.invoke('SendOffer', data);
alert(JSON.stringify(data));
}
});
client.peer = peer;
}
//peer not init to pass the answer
function CreateAnswer(offer) {
let peer = InitPeer('notInit');
let data = null;
peer.on('signal', (offer) => {
alert("Enter in to CreateAnswer");
connection.invoke('SendAnswer', offer);
});
peer.signal(offer);
}
//this fuction will run when answer send from server
function SignalAnswer(answer) {
alert("Enter in to Signaling");
client.gotAnswer = true;
let peer = client.peer;
peer.signal(answer);
};
//this function will create video
function CreateVideo(stream) {
alert("video play");
let video = document.createElement('video');
video.id = 'peerVideo';
video.style.width = '400px';
video.style.height = '400px';
video.srcObject = stream;
video.class = 'embed-responsive-item';
document.querySelector("#peerDiv").appendChild(video);
video.play();
}
function SessionActive() {
document.write("User is in another call.Please come back");
}
//Hub will call this function to create the offer
connection.on("CreateOffer", function () {
alert("Enter in to CreateOffer");
CreatePeer();
});
//Hub will call this method to create the answer
connection.on("CreateAnswer", function (offer) {
alert("Enter in to CreateAnswer");
CreateAnswer(offer);
});
//Hub will call this fucntion to send the answer ot the caller
connection.on("SignalAnswer", function (answer) {
alert("Enter in to Signaling");
SignalAnswer(answer);
})
//Hub will call this fuction to this connect the video
connection.on("RemovePeer", function () {
document.getElementById('peerVideo').remove();
if (client.peer) {
client.peer.destroy();
}
});
})
.catch(err => document.write(err));
我在我的视频聊天应用程序中编写了 3 种方法,因为我是 javascript 新手,所以有一点困惑。在方法“SignalAnswer”中,它调用“peer.signal(answer)”,并调用“CreatePeer”中的信号函数。在“CreateAnswer”方法中也创建了一个信号函数,但它没有被调用。它将由 peer.signal(offer) 在同一方法中调用。我的猜测是因为 peer 会在两个不同的时间得到两个不同的对象。所以根据对象分配这个函数将被调用。任何人都可以解释一下。这些函数如何在 javascripts 中工作注意:连接用于调用 SingnalR 集线器。