经过重新协商,onaddstream从未打过电话

onaddstream never called after re-negotiation

本文关键字:onaddstream 电话 新协商 协商 经过      更新时间:2023-09-26

我正在使用WebRTC创建一个测试视频聊天应用程序。我有两个同伴成功连接。我想为用户添加一种"重新连接"的方式(断开连接并与另一个用户连接。出于测试目的,"另一个"用户与以前相同)。因此,当选择一个按钮时,该代码被称为:

send(userId, toUserId, {disconnect: "true"});
pc.removeStream(localStream);
pc.close();
pc = new PeerConnection(servers, options);
remoteVideo.src = "";

在上面的代码中,使用信令方法,向另一个用户发送一条消息,提醒他们断开连接。然后,从对等连接中删除本地流,关闭连接,创建新的对等连接,并在加载其他视频时将远程视频设置为空白。之后,我有一些代码可以找到另一个要连接的用户(测试用例中的同一用户),并继续进行协商(遵循之前用于协商的相同代码)。

使用日志记录,似乎每一步都达到了(offer/answer/icecandidate)。问题是始终无法连接到onaddstream侦听器。是的,在发送报价之前会调用pc。addStream()。我正在使用一个包含流的变量(localStream),这样我就不必再请求权限了。我不确定这是否是问题所在。我的问题是:为什么没有调用一个ddstream?

编辑:这里还有一些代码。单击按钮时调用的方法:

function restart(){
    send(userId, toUserId, {disconnect: "true"});
    pc.removeStream(localStream);
    pc.close();
    pc = new PeerConnection(servers, options);
    remoteVideo.src = "";
    $.ajax({
        url: "http://localhost:8080/UserInterface/rs/message/creds/" + '#{sessionHandler.username}',
        type: "GET",
        success: function(data){
            data = JSON.parse(data);
            if (data != null){
                toUserId = data.toUserId;
                activeUser = data.activeUser;
                activeUser = JSON.parse(activeUser);
            }
            pc.addStream(localStream);
            sendOffer();
        }
    });
}

在上面的代码中,localStream变量是在第一次调用getUserMedia()方法时获得的。这样,当我需要流时,我就不必再调用它了。sendOffer()方法:

function sendOffer(){
    pc.onicecandidate = iceCandidateFound;
    if (activeUser){
        $.ajax({
            url: "http://localhost:8080/UserInterface/rs/message/sessId/" + toUserId,
            type: "GET",
            success: function(data){
                toSessionId = data;
                pc.createOffer(function (offer) {
                    pc.setLocalDescription(offer);
                    var offerMessage = {
                        "offer": offer,
                    };
                    send(userId, toUserId, offerMessage);
                }, errorHandler, constraints);
            }
        });
    }
}

使用日志记录和chrome://webrtc-internals可以看出,所有适当的步骤都已成功完成(例如offer/answer)。包括信令在内的其余代码与第一次连接时使用的代码完全相同,第一次连接运行良好。唯一的问题是从来没有调用过一个ddstream。

我的问题的解决方案非常简单,我完全忽略了这一点。我忘记在新的PeerConnection对象的ddstream中重新声明事件侦听器。在我有这样的东西之前:

pc.onaddstream = function(ev){
    console.log("onaddstream");
    remoteVideo.src = URL.createObjectURL(ev.stream);
};

这对第一次视频连接来说效果很好。但是,在restart()方法中,我重新实例化了pc对象。像这样:

pc = new PeerConnection(servers, options);

但是,我没有将事件侦听器放回对象上。所以,我做了一个函数:

function remoteStreamAdded(ev){
    console.log("onaddstream");
    remoteVideo.src = URL.createObjectURL(ev.stream);
}

而且,每当我需要放置事件侦听器时,我都可以调用此方法,如下所示:

pc = new PeerConnection(servers, options);
pc.onaddstream = remoteStreamAdded;