无法使用onaddstream函数

时间:2017-01-06 16:43:50

标签: javascript node.js

请帮忙 我首先使用datachannel api创建我的聊天文本,并且它已成功运行 但问题是,当我尝试添加呼叫视频时,我得到本地流,但我可以通过函数ondatastream获取远程流,因为我认为它没有被执行 这是我的代码是我做错了什么? 谢谢你的帮助

$("#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)
    })
}

1 个答案:

答案 0 :(得分:0)

您在peerConnection.addStream()之后发送peerConnection.createOffer()并发送商品。 (peerConnection.onnegotiationneeded事件很容易使用)