Поток получен, но не отображается в элементе видео html только для нескольких подключений - PullRequest
0 голосов
/ 27 декабря 2018

Я пытаюсь написать код ОБМЕНА ЭКРАНОМ, используя WebRTC и socket.io, используя расширение Chrome для видеоконференций.

Я могу подключиться к многопользовательскому режиму в моем веб-приложении.

Iвызовите sendStream () и установите peerConn.addTrack (track, stream) после того, как этот peerConn.ontrack () вызывается для каждого соединения (клиента).

Я получаю поток через getUserMedia ()

var sharedScreen = document.querySelector('#shared-screen');
sharedScreen.srcObject = remoteStream;

Но я застрял в какой-то момент: когда я установил соединение один к одному, я получил поток в peerConn.ontrack () и могу правильно показать поток в элементе видео

но для мульти-соединения (один ко многим) peerConn.ontrack () вызвал и получил поток, но не смог показать поток в элементе видео в формате html.Поток получен, но не показан в элементе видео только в этом случае. (Не могли бы вы указать причину) *

function sendStream(stream) {
    console.log('UI: sendStream() ', stream);
    if (typeof stream !== 'undefined') {
        console.log('UI: creating peer connection in sendStream()');

        stream.getTracks().forEach(function(track) {
            // adding tracks
            peerConn.addTrack(track, stream);
        });

        console.log('isInitiator', isInitiator);
        if (isInitiator) {
            peerConn.createOffer(offerOptions).then(function(offer) {
                onLocalSessionCreated(offer);
            })
        }
    }else{
        alert("stream is:" + typeof(stream));
    }
}

/**************************************************************************** 
 * WebRTC peer connection and data channel
 ****************************************************************************/

var peerConn;
var dataChannel;

function signalingMessageCallback(message) {
    console.log('Client received message:', message);
    if (message.type === 'offer') {
        console.log('Got offer. Sending answer to peer.');
        peerConn.setRemoteDescription(new RTCSessionDescription(message)).then(()=>{
            console.log("Answer creating");
            peerConn.createAnswer().then((answer) => {
                console.log("Answer creating > ",answer)
                onLocalSessionCreated(answer);
            }, logError)
        })
        .catch(logError);

    } else if (message.type === 'answer') {
        console.log('Got answer.');
        peerConn.setRemoteDescription(new RTCSessionDescription(message), function(){}, logError);

    } else if (message.type === 'candidate') {
        console.log('Adding ICECandidate : peerConn.addIceCandidate()');
        peerConn.addIceCandidate(new RTCIceCandidate({candidate: message.candidate, sdpMLineIndex: message.label}));

    } else if (message === 'bye') {
        // TODO: cleanup RTC connection?
    }
}

function createPeerConnection(isInitiator, config) {
    console.log('Creating Peer connection as initiator?', isInitiator, 'config:', config);
    peerConn = new RTCPeerConnection(RTCConfiguration);

    // send any ice candidates to the other peer
    peerConn.onicecandidate = function (event) {
        console.log('onIceCandidate event:', event);
        if (event.candidate) {
            sendMessage({
                type: 'candidate',
                label: event.candidate.sdpMLineIndex,
                id: event.candidate.sdpMid,
                candidate: event.candidate.candidate
            });
        } else {
            console.log('End of candidates.');
        }
    };
    // called for each connection
    // stream received for each connection
    // but not showing in video element only for multi connection  
    // successfully showing for peer connection 
    peerConn.ontrack = function(event){
        console.log("stream added: peerConn.ontrack", event.streams[0], event.streams[0].id);
        let remoteStream = event.streams[0];
        sharedScreen.srcObject = remoteStream;
        var playPromise = sharedScreen.play();

        // playPromise won’t be defined.
        if (playPromise !== undefined) {
            playPromise.then(function() {
                // Automatic playback started!
            }).catch(function(error) {
                console.log("ontrack: error", error);
            });
        }
    }
}

function onLocalSessionCreated(desc) {
    console.log('local session created:', desc);
    peerConn.setLocalDescription(desc, function () {
        console.log('sending local desc:', peerConn.localDescription);
        sendMessage(peerConn.localDescription);
    }, logError);
}

function onDataChannelCreated(channel) {
    console.log('onDataChannelCreated:', channel);

    channel.onopen = function () {
        console.log('CHANNEL opened!!!');
    };

    channel.onmessage = (webrtcDetectedBrowser == 'firefox') ? 
        receiveDataFirefoxFactory() :
        receiveDataChromeFactory();
}

function receiveDataChromeFactory() {
    return function onmessage(event) {
        console.log("data received : channel.onmessage");
        debugger;
    }
}   

function receiveDataFirefoxFactory() {
    return function onmessage(event) {
        console.log("data received : channel.onmessage");
        debugger;
    }
}

И не могли бы вы предоставить хороший ресурс, который я может реализовать веб-приложение для видеоконференций и обмена экранами для отраслевого уровня (может принимать более 1000 клиентов одновременно за несколько сеансов).Я слышал о SFU / MCU Janus WebRTC Server и т. Д.

Помощь будет принята с благодарностью.Удачного кодирования.

...