Javascript 无法使用onaddstream函数获取远程流
请帮忙 我已经使用datachannel api创建了我的聊天文本,并成功地完成了工作 但问题是,当我尝试添加呼叫视频时,我得到了本地流,但我可以通过ondatastream函数得到远程流,因为我认为它没有被执行 这是我的密码我做错什么了吗? 谢谢你帮助我Javascript 无法使用onaddstream函数获取远程流,javascript,node.js,Javascript,Node.js,请帮忙 我已经使用datachannel api创建了我的聊天文本,并成功地完成了工作 但问题是,当我尝试添加呼叫视频时,我得到了本地流,但我可以通过ondatastream函数得到远程流,因为我认为它没有被执行 这是我的密码我做错什么了吗? 谢谢你帮助我 $("#sendform").submit(sendDirect); $(".user2").click(connectTo); $("#send").click(sendDirect); $('#zoneChat').hide(); var
$("#sendform").submit(sendDirect);
$(".user2").click(connectTo);
$("#send").click(sendDirect);
$('#zoneChat').hide();
var ws = null;
var user = "";
var user2 = "";
var localVideo=document.getElementById('localvideo');
var remoteVideo=document.getElementById('remotevideo');
var config = { "iceServers":[{ "urls":"stun:stun.l.google.com:19302" }] };
var connection = { };
var peerConnection;
var dataChannel;
$(document).ready(function(){
$(".user2").click(function(){
$('#chat_messages').empty();
user2 = $(this).attr('id');
$('#pannelTitle').empty();
$('#pannelTitle').append('<span class="pull-right" ><a href="#" id="videoControl">video call</a></span>')
$('#pannelTitle').append('<p>'+user2+'</p>');
$('#zoneChat').show();
});
//establish the connection to the ws
ws = new WebSocket("ws://127.0.0.1:8088");
ws.onopen = function(e){
console.log("Websocket opened");
}
ws.onclose = function(e){
console.log("Websocket closed");
}
ws.onmessage = function(e){
console.log("Websocket message received: " + e.data);
var json = JSON.parse(e.data);
if(json.action == "candidate"){
if(json.to == user){
processIce(json.data);
}
} else if(json.action == "offer"){
// incoming offer
if(json.to == user){
user2 = json.from;
processOffer(json.data)
}
} else if(json.action == "answer"){
// incoming answer
if(json.to == user){
processAnswer(json.data);
}
}
// else if(json.action == "id"){
// userId = json.data;
// } else if(json.action=="newUser"){
// if(userId!=null && json.data!=userId){
// }
// }
}
ws.onerror = function(e){
console.log("Websocket error");
}
user = $(".user").attr('id');
console.log('my name '+user+' is added');
});
$(document).on('click','#videoControl',function(){
navigator.mediaDevices.getUserMedia({
audio: false,
video: true
}).then(
function(stream){
console.log('Received local stream');
localVideo.srcObject = stream;
// Add localStream to global scope so it's accessible from the browser console
window.localStream = localStream = stream;
peerConnection.addStream(localStream);
console.log('the stream is added');
}
).catch(function(e) {
console.log('getUserMedia() error: ' + e.name);
});
});
function setMyId(e){
e.preventDefault();
user = $(".user").attr('id');
console.log('my name '+user+' is added');
return false;
}
function connectTo(e){
e.preventDefault();
console.log('the datachannel is oppened with'+user2);
openDataChannel();
var sdpConstraints = { offerToReceiveAudio: true, offerToReceiveVideo: false }
peerConnection.createOffer(sdpConstraints).then(function (sdp) {
peerConnection.setLocalDescription(sdp);
sendNegotiation("offer", sdp);
console.log("------ SEND OFFER ------");
}, function (err) {
console.log(err)
});
}
function sendDirect(e){
e.preventDefault();
dataChannel.send($("#message").val());
$('#chat_messages').append('<div class="message"><span style="font-weight: bolder;">Me: </span>'+$("#message").val()+'</div>');
console.log("Sending over datachannel: " + $("#message").val());
$("#message").val('');
}
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
}
function openDataChannel (){
peerConnection = new RTCPeerConnection(config, connection);
peerConnection.onicecandidate = function(e){
if (!peerConnection || !e || !e.candidate) return;
var candidate = e.candidate;
sendNegotiation("candidate", candidate);
}
//when a remote user adds stream to the peer connection, we display it
peerConnection.onaddstream= function(e) {
remoteVideo.srcObject = e.stream;
console.log('pc2 received remote stream');
};
dataChannel = peerConnection.createDataChannel("datachannel", { reliable: false });
dataChannel.onopen = function(){ console.log("------ DATACHANNEL OPENED ------");};
dataChannel.onclose = function(){
$('#chat_messages').append('<div class="message from"><p style="color:#ccc;">'+user2+' left the chat</p></div>');
console.log("------ DC closed! ------")
};
dataChannel.onerror = function(){
console.log("DC ERROR!!!")
};
peerConnection.ondatachannel = function (ev) {
console.log('peerConnection.ondatachannel event fired.');
ev.channel.onopen = function() {
console.log('Data channel is open and ready to be used.');
};
ev.channel.onmessage = function(e){
$('#zoneChat').show();
$('#pannelTitle').empty();
$('#pannelTitle').append('<p>'+user2+'</p>');
console.log("DC from ["+user2+"]:" +e.data);
$('#chat_messages').append('<div class="message from"><span style="font-weight: bolder;">'+user2+': </span>'+e.data+'</div>');
}
};
return peerConnection
}
function sendNegotiation(type, sdp){
var json = { from: user, to: user2, action: type, data: sdp};
ws.send(JSON.stringify(json));
console.log("Sending ["+user+"] to ["+user2+"]: " + JSON.stringify(sdp));
}
function processOffer(offer){
var peerConnection = openDataChannel();
peerConnection.setRemoteDescription(new RTCSessionDescription(offer)).catch(e => {
console.log(e);
});
var sdpConstraints = {
'mandatory': {
'OfferToReceiveAudio': false,
'OfferToReceiveVideo': false
}
};
peerConnection.createAnswer(sdpConstraints).then(function (sdp) {
return peerConnection.setLocalDescription(sdp).then(function() {
sendNegotiation("answer", sdp);
console.log("------ SEND ANSWER ------");
})
}, function(err) {
console.log(err)
});
console.log("------ PROCESSED OFFER ------");
};
function processAnswer(answer){
peerConnection.setRemoteDescription(new RTCSessionDescription(answer));
console.log("------ PROCESSED ANSWER ------");
return true;
};
function processIce(iceCandidate){
peerConnection.addIceCandidate(new RTCIceCandidate(iceCandidate)).catch(e => {
debugger
console.log(e)
})
}
$(“#sendform”)。提交(sendDirect);
$(“.user2”)。单击(连接到);
$(“#发送”)。单击(直接发送);
$('#zoneChat').hide();
var-ws=null;
var user=“”;
var user2=“”;
var localVideo=document.getElementById('localVideo');
var remoteVideo=document.getElementById('remoteVideo');
var config={“iceServers”:[{“URL”:“stun:stun.l.google.com:19302”}]};
var连接={};
var-peerConnection;
var数据通道;
$(文档).ready(函数(){
$(“.user2”)。单击(函数(){
$(“#聊天室消息”).empty();
user2=$(this.attr('id');
$('#panneltile').empty();
$('#panneltile')。附加('')
$(“#panneltite”).append(“”+user2+””);
$('#zoneChat').show();
});
//建立与ws-Server的连接
ws=newwebsocket(“ws://127.0.0.1:8088”);
ws.onopen=函数(e){
日志(“Websocket已打开”);
}
ws.onclose=函数(e){
日志(“Websocket关闭”);
}
ws.onmessage=函数(e){
日志(“接收到Websocket消息:”+e.data);
var json=json.parse(e.data);
if(json.action==“候选”){
if(json.to==用户){
processIce(json.data);
}
}else if(json.action==“offer”){
//来盘
if(json.to==用户){
user2=json.from;
processOffer(json.data)
}
}else if(json.action==“应答”){
//收到的答复
if(json.to==用户){
processAnswer(json.data);
}
}
//else if(json.action==“id”){
//userId=json.data;
//}else if(json.action==“newUser”){
//if(userId!=null&&json.data!=userId){
// }
// }
}
ws.onerror=函数(e){
日志(“Websocket错误”);
}
user=$(“.user”).attr('id');
log('添加了我的名字'+用户+');
});
$(文档)。在('单击','视频控制',函数()上){
navigator.mediaDevices.getUserMedia({
音频:错,
视频:真的
}).那么(
功能(流){
log(“接收到的本地流”);
localVideo.srcObject=流;
//将localStream添加到全局范围,以便可以从浏览器控制台访问它
window.localStream=localStream=stream;
peerConnection.addStream(localStream);
log(“添加了流”);
}
).catch(函数(e){
log('getUserMedia()错误:'+e.name);
});
});
函数setMyId(e){
e、 预防默认值();
user=$(“.user”).attr('id');
log('添加了我的名字'+用户+');
返回false;
}
函数连接到(e){
e、 预防默认值();
log('datachannel被'+user2'打开);
openDataChannel();
var sdpConstraints={offerToReceiveAudio:true,offerToReceiveVideo:false}
createOffer(sdpConstraints)。然后(函数(sdp){
peerConnection.setLocalDescription(sdp);
谈判(“要约”,sdp);
console.log(“----发送报价----”;
},函数(err){
console.log(错误)
});
}
函数sendDirect(e){
e、 预防默认值();
dataChannel.send($(“#message”).val());
$('chat_messages').append('Me:'+$(“#messages”).val()+'';
log(“通过数据通道发送:+$(“#消息”).val();
$(“#消息”).val(“”);
}
函数getURLParameter(名称){
返回decodeURIComponent((新的RegExp('[?&]'+name+'='+'([^&]+?)(&&| | | | | | | | | | | |$)).exec(location.search)| |[,'')[1]。replace(/\+/+//g,'%20'))| | null
}
函数openDataChannel(){
peerConnection=新的RTCPeerConnection(配置,连接);
peerConnection.onicecandidate=函数(e){
如果(!peerConnection | | |!e | |!e.candidate)返回;
var候选者=e候选者;
谈判(“候选人”,候选人);
}
//当远程用户向对等连接添加流时,我们会显示它
peerConnection.onaddstream=函数(e){
remoteVideo.srcObject=e.stream;
log('pc2接收到远程流');
};
dataChannel=peerConnection.createDataChannel(“dataChannel”,{reliable:false});
dataChannel.onopen=function(){console.log(“----dataChannel-OPENED------”;};
dataChannel.onclose=函数(){
$(“#聊天室消息”)。追加(“”+user2+”离开聊天室);
console.log(“----DC closed!”)
};
dataChannel.onerror=函数(){
console.log(“DC错误!!!”)
};
peerConnection.ondatachannel=功能(ev){
log('peerConnection.ondatachannel事件已激发');
ev.channel.onopen=函数(){
log('数据通道已打开并准备好使用');
};
ev.channel.onmessage=函数(e){
$('#zoneChat').show();
$('#panneltile').empty();
$(“#panneltite”).append(“”+user2+”
”);
console.log(“DC from[“+user2+”]:“+e.data”);
$('chat_messages')。追加(''+user2+':'+e.data+'');
}
};
回电连接
}
函数sendNegotiation(类型,sdp){
var json={from:user,to:user2,action:type,data:sdp};
send(JSON.stringify(JSON));
log(“发送[“+user+”]到[“+user2+”]:“+JSON.stringify(sdp));
}
函数processOffer(offer){
var peerConnection=openDataChannel();
peerConnection.setRemoteDescription(新的RTCSessionDescription(提供)).catch(e=>{
控制台日志(e);
});
var sdpConstraints={
“强制性”:{