Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejs
themeRDark
    connection = Flashphoner.roomApi.connect({urlServer: url, username: username}).on(SESSION_STATUS.FAILED, function(session){
        setStatus('#status', session.status());
 ...
       onLeft();
    }).on(SESSION_STATUS.DISCONNECTED, function(session) {
        setStatus('#status', session.status());
  ...
      onLeft();
    }).on(SESSION_STATUS.ESTABLISHED, function(session) {
        setStatus('#status', session.status());
        joinRoom();
    });

...

Code Block
languagejs
themeRDark
    connection.join({name: getRoomName()}).on(ROOM_EVENT.STATE, function(room){
        var participants = room.getParticipants();
        console.log("Current number of participants in the room: " + participants.length);
        if (participants.length >= _participants) {
            console.warn("Current room is full");
            $("#failedInfo").text("Current room is full.");
            room.leave().then(onLeft, onLeft);
            return false;
        }
        room_ = room;
        setInviteAddress(room.name());
        if (participants.length > 0) {
            var chatState = "participants: ";
            for (var i = 0; i < participants.length; i++) {
                installParticipant(participants[i]);
                chatState += participants[i].name();
                if (i != participants.length - 1) {
                    chatState += ",";
                }
            }
            addMessage("chat", chatState);
        } else {
            addMessage("chat", " room is empty");
        }
        publishLocalMedia(room);
        onJoined(room);
    }).on(ROOM_EVENT.JOINED, function(participant){
        installParticipant(participant);
        addMessage(participant.name(), "joined");
    }).on(ROOM_EVENT.LEFT, function(participant){
        //remove participant
        removeParticipant(participant);
        addMessage(participant.name(), "left");
    }).on(ROOM_EVENT.PUBLISHED, function(participant){
        playParticipantsStream(participant);
    }).on(ROOM_EVENT.FAILED, function(room, info){
        connection.disconnect();
        $('#failedInfo').text(info);
    }).on(ROOM_EVENT.MESSAGE, function(message){
        addMessage(message.from.name(), message.text);
    });

5. Получение от сервера события, описывающего статус комнаты

RoomStatusEvent STATE код

При получении данного события:

  • определяется количество участников конференции с помощью метода room.getParticipants(), который возвращает массив объектов participant,
  • если к конференции уже присоединилось максимально допустимое количество участников, производится выход из "комнаты" при помощи room.leave()
  • если количество участников меньше максимально допустимого, начинается публикация видеопотока
Code Block
languagejs
themeRDark
   connection.join({name: getRoomName()}).on(ROOM_EVENT.STATE, function(room){
        var participants = room.getParticipants();
        console.log("Current number of participants in the room: " + participants.length);
        if (participants.length >= _participants) {
            console.warn("Current room is full");
            $("#failedInfo").text("Current room is full.");
            room.leave().then(onLeft, onLeft);
            return false;
        }
        room_ = room;
        setInviteAddress(room.name());
        if (participants.length > 0) {
            var chatState = "participants: ";
            for (var i = 0; i < participants.length; i++) {
                installParticipant(participants[i]);
                chatState += participants[i].name();
                if (i != participants.length - 1) {
                    chatState += ",";
                }
            }
            addMessage("chat", chatState);
        } else {
            addMessage("chat", " room is empty");
        }
        publishLocalMedia(room);
        onJoined(room);
    }).on(ROOM_EVENT.JOINED, function(participant){
        installParticipant(participant);
        addMessage(participant.name(), "joined");
    }).on(ROOM_EVENT.LEFT, function(participant){
        //remove participant
        removeParticipant(participant);
        addMessage(participant.name(), "left");
    }).on(ROOM_EVENT.PUBLISHED, function(participant){
        playParticipantsStream(participant);
    }).on(ROOM_EVENT.FAILED, function(room, info){
        connection.disconnect();
        $('#failedInfo').text(info);
    }).on(ROOM_EVENT.MESSAGE, function(message){
        addMessage(message.from.name(), message.text);
    });

...

room.publish() код

При публикации передаются параметры:

  • параметры видео: ширина, высота, количество кадров в секунду, источник (экран)
  • элемент страницы для отображения превью
Code Block
languagejs
themeRDark
 var constraints = {
        video: {
            width: parseInt($('#width').val()),
            height: parseInt($('#height').val()),
            frameRate: parseInt($('#fps').val()),
        },
        audio: $("#useMic").prop('checked')
    };
    constraints.video.type = "screen";
    if (Browser.isFirefox()){
        constraints.video.mediaSource = "screen";
    }
    room.publish({
        display: document.getElementById("preview"),
        constraints: constraints,
        name: "screenShare",
        cacheLocalResources: false
    }).on(STREAM_STATUS.FAILED, function (stream) {
        console.warn("Local stream failed!");
        onStopSharing();
    }).on(STREAM_STATUS.PUBLISHING, function (stream) {
        /*
         * User can stop sharing screen capture using Chrome "stop" button.
         * Catch onended video track event and stop publishing.
         */
        document.getElementById(stream.id()).srcObject.getVideoTracks()[0].onended = function (e) {
            stream.stop();
        };
        document.getElementById(stream.id()).addEventListener('resize', function(event){
            resizeVideo(event.target);
        });
        onStartSharing(stream);
    }).on(STREAM_STATUS.UNPUBLISHED, function(stream) {
        onStopSharing();
    });

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

RoomStatusEvent JOINED код

Code Block
languagejs
themeRDark
connection.join({name: getRoomName()}).on(ROOM_EVENT.STATE, function(room){
        var participants = room.getParticipants();
        console.log("Current number of participants in the room: " + participants.length);
        if (participants.length >= _participants) {
            console.warn("Current room is full");
            $("#failedInfo").text("Current room is full.");
            room.leave().then(onLeft, onLeft);
            return false;
        }
        room_ = room;
        setInviteAddress(room.name());
        if (participants.length > 0) {
            var chatState = "participants: ";
            for (var i = 0; i < participants.length; i++) {
                installParticipant(participants[i]);
                chatState += participants[i].name();
                if (i != participants.length - 1) {
                    chatState += ",";
                }
            }
            addMessage("chat", chatState);
        } else {
            addMessage("chat", " room is empty");
        }
        publishLocalMedia(room);
        onJoined(room);
    }).on(ROOM_EVENT.JOINED, function(participant){
        installParticipant(participant);
        addMessage(participant.name(), "joined");
    }).on(ROOM_EVENT.LEFT, function(participant){
        //remove participant
        removeParticipant(participant);
        addMessage(participant.name(), "left");
    }).on(ROOM_EVENT.PUBLISHED, function(participant){
        playParticipantsStream(participant);
    }).on(ROOM_EVENT.FAILED, function(room, info){
        connection.disconnect();
        $('#failedInfo').text(info);
    }).on(ROOM_EVENT.MESSAGE, function(message){
        addMessage(message.from.name(), message.text);
    });

...

RoomStatusEvent PUBLISHED код

...
    });


5. Получение от сервера события, описывающего статус комнаты

RoomStatusEvent STATE код

При получении данного события:

  • определяется количество участников конференции с помощью метода room.getParticipants(), который возвращает массив объектов participant,
  • если к конференции уже присоединилось максимально допустимое количество участников, производится выход из "комнаты" при помощи room.leave()
  • если количество участников меньше максимально допустимого, начинается публикация видеопотока
Code Block
languagejs
themeRDark
   connection.join({name: getRoomName()}).on(ROOM_EVENT.STATE, function(room){
        var participants = room.getParticipants();
        console.log("Current number of participants in the room: " + participants.length);
        if (participants.length >= _participants) {
            console.warn("Current room is full");
            $("#failedInfo").text("Current room is full.");
            room.leave().then(onLeft, onLeft);
            return false;
        }
        room_ = room;
        setInviteAddress(room.name());
        if (participants.length > 0) {
            var chatState = "participants: ";
            for (var i = 0; i < participants.length; i++) {
                installParticipant(participants[i]);
                chatState += participants[i].name();
                if (i != participants.length - 1) {
                    chatState += ",";
                }
            }
            addMessage("chat", chatState);
        } else {
            addMessage("chat", " room is empty");
        }
        publishLocalMedia(room);
        onJoined(room);
    }).on(ROOM_EVENT.JOINED, function(participant){
        installParticipant(participant);
        addMessage(participant.name(), "joined");
    }).on(ROOM_EVENT.LEFT, function(participant){
        //remove participant
        removeParticipant}).on(ROOM_EVENT.LEFT, function(participant);{
        addMessage(participant.name(), "left");...
    }).on(ROOM_EVENT.PUBLISHED, function(participant){
        playParticipantsStream(participant);...
    }).on(ROOM_EVENT.FAILED, function(room, info){
        connection.disconnect();
        $('#failedInfo').text(info);...
    }).on(ROOM_EVENT.MESSAGE, function(message){
        addMessage(message.from.name(), message.text);...
    });


96. Воспроизведение видеопотока от другого участникаparticipant.playПубликация видеопотока с экрана.

room.publish() код

Параметром передается div-элемент, в котором будет отображаться видео, в зависимости от источника - веб-камера или экран

...

languagejs
themeRDark

...

При публикации передаются параметры:

  • параметры видео: ширина, высота, количество кадров в секунду, источник (экран)
  • элемент страницы для отображения превью
Code Block
languagejs
themeRDark
 var constraints = {
        video: {
            width: parseInt($('#width').val()),
            forheight: (var i=0; i<participant.getStreams().length; i++) {
parseInt($('#height').val()),
            frameRate: parseInt($("[id$=Name]"'#fps').each(function (index, value) {val()),
        },
        ifaudio: ($(value"#useMic").textprop('checked') == participant.name
    };
    constraints.video.type = "screen";
    if (Browser.isFirefox()) {
        constraints.video.mediaSource = "screen";
    }
      var p = value.id.replace('Name', '');
room.publish({
        display: document.getElementById("preview"),
        constraints: constraints,
    var pDisplay = p + 'Display';name: "screenShare",
        cacheLocalResources: false
        ...
   // check if we already play this stream
    });


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

RoomStatusEvent JOINED код

Code Block
languagejs
themeRDark
    connection.join({name: getRoomName()}).on(ROOM_EVENT.STATE, function(room){
        ...
         if (document.getElementById(participant.getStreams()[i].id()) == null) }).on(ROOM_EVENT.JOINED, function(participant){
        installParticipant(participant);
                // setup 1st stream to main divaddMessage(participant.name(), "joined");
    }).on(ROOM_EVENT.LEFT, function(participant){
        ...
    }).on(ROOM_EVENT.PUBLISHED, function(participant){
        ...
   if (participant.getStreams()[i].streamName().indexOf("screenShare") == -1) }).on(ROOM_EVENT.FAILED, function(room, info){
        ...
    }).on(ROOM_EVENT.MESSAGE, function(message){
        ...
    });


8. Получение от сервера события, сигнализирующего о публикации видеопотока другим участником

RoomStatusEvent PUBLISHED код

Code Block
languagejs
themeRDark
    participantconnection.getStreams()[i].play(document.getElementById(pDisplay)join({name: getRoomName()}).on(STREAMROOM_STATUSEVENT.PLAYINGSTATE, function (playingStreamroom) {
        ...
                        document.getElementById(playingStream.id()).addEventListener('resize', function (event) {
           }).on(ROOM_EVENT.JOINED, function(participant){
        ...
    }).on(ROOM_EVENT.LEFT, function(participant){
        ...
    resizeVideo(event.target);}).on(ROOM_EVENT.PUBLISHED, function(participant){
        playParticipantsStream(participant);
    }).on(ROOM_EVENT.FAILED,           function(room, info){
         });...
    }).on(ROOM_EVENT.MESSAGE, function(message){
        ...
        });


9. Воспроизведение видеопотока от другого участника

participant.play() код

Параметром передается div-элемент, в котором будет отображаться видео, в зависимости от источника - веб-камера или экран

Code Block
languagejs
themeRDark
function playParticipantsStream(participant) {
    if (participant.getStreams().length > }0); {
        for (var i=0;              } else {
                i<participant.getStreams().length; i++) {
            participant.getStreams$()"[i].play(document.getElementById("sharedDisplay")).on(STREAM_STATUS.PLAYING, function (playingStreamid$=Name]").each(function (index, value) {
                                document.getElementById(playingStream.id()).addEventListener('resize', function (eventif ($(value).text() == participant.name()) {
                       var p = value.id.replace('Name', '');
         resizeVideo(event.target);
           var pDisplay = p + 'Display';
                });
    // check if we already play this stream
                 });
   if (document.getElementById(participant.getStreams()[i].id()) == null) {
                 }
       // setup 1st stream to main div
       }
                }
 if (participant.getStreams()[i].streamName().indexOf("screenShare") == -1) {
       });
        }
    }
}

10. Остановка публикации видеопотока.

stream.stop() код

Code Block
languagejs
themeRDark
function onMediaPublished(stream) {
         $("#localStopBtn").text("Stop").off('click').click(function()participant.getStreams()[i].play(document.getElementById(pDisplay)).on(STREAM_STATUS.PLAYING, function (playingStream) {
        $(this).prop('disabled', true);
           stream.stop();
    }).prop('disabled', false);
         $("#localAudioToggle").text("Mute A").off('click').click(function()document.getElementById(playingStream.id()).addEventListener('resize', function (event) {
        if (stream.isAudioMuted()) {
               $(this).text("Mute A");
            stream.unmuteAudio(resizeVideo(event.target);
  
      } else {
            $(this).text("Unmute A");
            stream.muteAudio(});
        }
    }).prop('disabled', false);
    $("#localVideoToggle").text("Mute V").off('click').click(function() {
        if (stream.isVideoMuted()) {
 });
             $(this).text("Mute V");
          }  stream.unmuteVideo();else {
        } else {
                    $participant.getStreams(this).text("Unmute V");
[i].play(document.getElementById("sharedDisplay")).on(STREAM_STATUS.PLAYING, function (playingStream) {
                stream.muteVideo();
        }
    }).prop('disabled',false);
    $("#shareBtn"document.getElementById(playingStream.id()).propaddEventListener('disabled',false);
}

11. Получение от сервера события, подтверждающего остановку публикации.

StreamStatusEvent UNPUBLISHED код

Code Block
languagejs
themeRDark
 room.publish(resize', function (event) {
        display: document.getElementById("preview"),
        constraints: constraints,
        name: "screenShare",
        cacheLocalResources: false resizeVideo(event.target);
    }).on(STREAM_STATUS.FAILED, function (stream) {
                  console.warn("Local stream failed!");
        onStopSharing(});
    }).on(STREAM_STATUS.PUBLISHING, function (stream) {
            /*
         * User can stop});
 sharing screen capture using Chrome "stop" button.
         * Catch onended video track event and stop publishing.}
         */
        document.getElementById(stream.id()).srcObject.getVideoTracks()[0].onended = function (e) {
     }
              stream.stop();  }
            });
        document.getElementById(stream.id()).addEventListener('resize', function(event}
    }
}


10. Остановка публикации видеопотока.

stream.stop() код

Code Block
languagejs
themeRDark
function onMediaPublished(stream) {
    $("#localStopBtn").text("Stop").off('click').click(function(){
            resizeVideo(event.target);
        }$(this).prop('disabled', true);
        onStartSharingstream.stop(stream);
    }).on(STREAM_STATUS.UNPUBLISHED, function(stream) {
        onStopSharing(prop('disabled', false);
    ...
});

12. Выход из комнаты чата.


room.leave() 11. Получение от сервера события, подтверждающего остановку публикации.

StreamStatusEvent UNPUBLISHED код

Code Block
languagejs
themeRDark
function onJoined(room) {
    $("#joinBtn").text("Leave").off('click').click(function()room.publish({
        $(this).prop('disabled', true);
display: document.getElementById("preview"),
         room.leave().then(onLeft, onLeft);constraints: constraints,
    }).prop('disabled', false);
   name: $("#shareBtn").prop('disabled',false);
    $('#sendMessageBtn').off('click').click(function(){screenShare",
        var message = field('message');cacheLocalResources: false
    }).on(STREAM_STATUS.FAILED, function   addMessage(connection.username(), message);(stream) {
        $('#message').val("");...
    }).on(STREAM_STATUS.PUBLISHING, function   //broadcast message
(stream) {
        ...
 var participants = room.getParticipants(); }).on(STREAM_STATUS.UNPUBLISHED, function(stream) {
        for (var i = 0; i < participants.length; i++onStopSharing();
    });


12. Выход из комнаты чата.

room.leave() код

Code Block
languagejs
themeRDark
function onJoined(room) {
    $("#joinBtn").text("Leave").off('click').click(function(){
        participants[i].sendMessage(message$(this).prop('disabled', true);
        } room.leave().then(onLeft, onLeft);
    }).prop('disabled', false);
    $('#failedInfo').text("");...
}