WebRTC-Experiment icon indicating copy to clipboard operation
WebRTC-Experiment copied to clipboard

How to start audio/video streaming on the request by user

Open imail2pankaj opened this issue 6 years ago • 6 comments

Hello @muaz-khan , I am working on a Project of group chat and it is working fine but sometimes streaming is not happening.

I am start streaming on joining of the room, so when any user joins the room streaming will start automatically, but I don't want to do that. I am creating list of users who joined the room and each user have camera icon beside the name in the list. By clicking on that camera icon want to stream for particular user. So if I have started streaming then all the users who joined the room will be able to see my cam. If they click on camera icon beside his name to start streaming then other users should be able to view his cam including me. If again he click on camera icon to disable camera then all the users will not be able to view his cam. Check below screenshot for more explanation.

chrome-edit

By default current user's camera icon will be visible. All the other user's camera icon will be hidden. Cam will be visible on the start of the streaming.

I have tried using below code, but only my cam start streaming not able to view cam on peer side.

myConnection.addStream({
    audio: true,
    video: true
});

ui.main.js You can get code from this link

var allConnections = new Array();

setInterval(CommonFunctions.joinedRoomUserCount, 300000);

var rtcMultiConnection = new RTCMultiConnection();
var summerNoteOptions = summernoteSettings();

var usersContainer = getElement('.users-container');

function getElement(selector) {
    return document.querySelector(selector);
}

function leaveRoomFromSession(room_id) {

    var store_message = CommonFunctions.setRoomLeftMessage($("#user_id").val());
    CommonFunctions.sendMessageAjax(room_id, $("#user_id").val(), $(store_message).html());

    CommonFunctions.setLocalStorage("is_room_streamed_" + room_id, 0);

    CommonFunctions.joinedRoomUserCount();

    var customEvent = {message: "room-counter", totalUsers: rtcMultiConnection.getAllParticipants().length, room_id: room_id};
    connectionSocket.socket.emit('room-count-users', customEvent);


    if (typeof rtcMultiConnection.attachStreams === "undefined") {
    } else {
        rtcMultiConnection.attachStreams.forEach(function (localStream) {
            var streamId = localStream.streamid;
            if (typeof streamId !== "undefined") {
                streamId = streamId.replace("{", "");
                streamId = streamId.replace("}", "");
                $('#' + streamId).parents(".item").remove();
                $('#' + streamId).remove();
            }
            localStream.stop();
        });
        rtcMultiConnection.leave();
    }
}
var main = getElement('.main');

$(document).on("click", '.continue', function (e) {
    // This line will start room session. user can join with this event
    e.preventDefault();

    var room_status = $(this).html();
    $(this).prop("disabled", true);
    $(this).html("Enter");
    $(this).tab('show');
    var yourName = main.querySelector('#your-name');
    var roomName = $(this).attr('data-room');

    var user_id = $("#user_id").val();

    if (!roomName) {
        roomName.focus();
        return alert('Your MUST Enter Room Name!');
    }

    localStorage.setItem('room-name', roomName);
    localStorage.setItem('user-name', yourName.value);

    var username = yourName.value || 'Anonymous';
    var myunique_identifier = username + "_" + role.toLowerCase() + "_" + user_id;

    rtcMultiConnection = initializeCon(room_id);

    rtcMultiConnection.extra.user_id = user_id;
    rtcMultiConnection.extra.username = username;
    rtcMultiConnection.extra.role = role.toLowerCase();
    rtcMultiConnection.extra.unique_identifier = myunique_identifier;
    rtcMultiConnection.extra.color = getRandomColor();
    var roomid = CommonFunctions.slug(roomName);
    rtcMultiConnection.channel = roomid;
    rtcMultiConnection.userid = myunique_identifier;
    rtcMultiConnection.sessionid = roomid;

    var userkey = CommonFunctions.userKeyString() + user_id;
    rtcMultiConnection.extra.userkey = userkey;

    setTimeout(function () {
        $(".chat-room").animate({
            scrollTop: $('.chat-room')[0].scrollHeight - $('.chat-room')[0].clientHeight
        }, 100);
    }, 2000);

    rtcMultiConnection.checkPresence(roomid, function (isRoomExists) {
        participantType = 0;
        if (!isRoomExists) {
            rtcMultiConnection.open(roomid);
        } else {
            addJoinLeftRoom({
                header: username,
                message: ' joined',
                userinfo: '<img src="images/action-needed.png">'
            }, room_id);
            rtcMultiConnection.join(roomid);
            participantType = 1;
        }
        joinRoom(room_id, user_id, participantType);
        var store_message = CommonFunctions.setRoomLeftMessage(username);

        var socket = rtcMultiConnection.getSocket();
        socket.on(rtcMultiConnection.socketCustomEvent, rtcMultiConnection.onCustomMessage);

        console.debug('room is present?', isRoomExists);
    });

    CommonFunctions.setLocalStorage("is_room_streamed_" + room_id, 0);
    allConnections.push({room_id: room_id, connection: rtcMultiConnection});
});


function getConnection(allConnections, room_id) {
    var connection = {};
    if (allConnections.length) {
        for (var cnt = 0; cnt < allConnections.length; cnt++) {
            if (allConnections[cnt].room_id = room_id) {
                return allConnections[cnt].connection;
            }
        }
    }
    return connection;
}


var isShiftKeyPressed = false;
var numberOfKeys = 0;
function userIsTyping(e, room_id) {

    if (e.keyCode == 16) {
        isShiftKeyPressed = true;
    }

    numberOfKeys++;
    if (numberOfKeys > 3)
        numberOfKeys = 0;

    if (!numberOfKeys) {
        if (e.keyCode == 8) {
            return rtcMultiConnection.send({
                stoppedTyping: true
            });
        }

        rtcMultiConnection.send({
            typing: true
        });
    }

    if (isShiftKeyPressed) {
        if (e.keyCode == 16) {
            isShiftKeyPressed = false;
        }
        return;
    }

    if (e.keyCode == 13 && !e.shiftKey) {
        sendChatMessage(room_id, 0);
    }
}

ui.peer-connection.js You can get code from this link


//Created function for initialize rtcmulticonnection.
function initializeCon(room_id) {
 
    window.enableAdapter = true; // enable adapter.js
    var rtcMultiConnection = new RTCMultiConnection();
    rtcMultiConnection.autoCreateMediaElement = false;
    rtcMultiConnection.dontCaptureUserMedia = true;
 
    rtcMultiConnection.socketMessageEvent = 'private-chat-demo';
 
    rtcMultiConnection.customStreams = {};
    rtcMultiConnection.renegotiatedSessions = {};
 
    rtcMultiConnection.session = {
        audio: false,
        video: false,
        data: true
    };
 
    var BandwidthHandler = rtcMultiConnection.BandwidthHandler;
    rtcMultiConnection.bandwidth = {
        audio: 50,
        video: 200,
        screen: 200
    };
 
    rtcMultiConnection.mediaConstraints = {
        video: false,
        audio: false
    };
 
    rtcMultiConnection.userid = session_username;
 
    rtcMultiConnection.extra = {
        username: session_username
    }
 
    rtcMultiConnection.optionalArgument = null;
 
    rtcMultiConnection.sdpConstraints.mandatory = {
        OfferToReceiveAudio: true,
        OfferToReceiveVideo: true
    };
 
    rtcMultiConnection.videosContainer = document.getElementById('videos-container-' + room_id);
 
    rtcMultiConnection.onstream = function (event) {
        event.mediaElement.removeAttribute('src');
        event.mediaElement.removeAttribute('srcObject');
 
        var video = document.createElement('video');
        video.controls = true;
        video.muted = true;
        if (event.type === 'local') {
            video.muted = true;
        }
        video.srcObject = event.stream;
 
        var width = 200;
        var mediaElement = getHTMLMediaElement(video, {
            title: event.extra.username,
            width: width,
            showOnMouseEnter: false,
            initiator: event.extra.username != session_username ? "hide" : "",
            streamId: event.streamid
        });
 
        if (event.extra.username == session_username) {
            var myVideosContainer = document.getElementById('my-webcam-container-' + room_id);
            myVideosContainer.appendChild(mediaElement);
 
            $("#my-webcam-container-" + room_id + " .usercam_" + event.extra.username).removeClass("hide");
            $(".room-" + room_id + "-mt-comment#online-user-items-" + event.extra.username + " a").addClass("user-active");
        } else {
            rtcMultiConnection.videosContainer.appendChild(mediaElement);
        }
        if (event.type === 'remote') {
            rtcMultiConnection.attachStreams.forEach(function (stream) {
                if (typeof stream.mute == "function") {
                    stream.mute("audio"); // mute all tracks
                }
            });
        }
        mediaElement.media.play();
        mediaElement.id = event.streamid;
 
    };
 
    rtcMultiConnection.onleave = function (event) {
        if (event.extra.username) {
            addJoinLeftRoom({
                header: event.extra.username,
                message: 'left',
                userinfo: "",
                color: event.extra.color
            }, room_id);
        }
 
    };
 
    var whoIsTyping = document.querySelector('#who-is-typing' + room_id);
    rtcMultiConnection.onmessage = function (e) {
 
        if (e.data.typing) {
            whoIsTyping.innerHTML = e.extra.username + ' is typing ...';
            return;
        }
        if (e.data.stoppedTyping) {
            whoIsTyping.innerHTML = '';
            return;
        }
 
        whoIsTyping.innerHTML = '';
        var isWhisper = false;
        var message = e.data;
        var whisperUser = "";
        if (e.data.indexOf("send-whisper-") > 0) {
            whisperUser = $(message, "span.whisper-message").html();
            isWhisper = true;
 
        }
        if (isWhisper && whisperUser == session_username) {
            addNewMessage({
                header: e.extra.username,
                message: ' ' + e.data,
                userinfo: "",
                color: e.extra.color
            }, room_id);
        } else if (!isWhisper && whisperUser === "") {
            addNewMessage({
                header: e.extra.username,
                message: ' ' + e.data,
                userinfo: "",
                color: e.extra.color
            }, room_id);
        }
    };
 
    rtcMultiConnection.onstreamended = function (event) {
        var mediaElement = document.getElementById(event.streamid);
        if (mediaElement) {
            mediaElement.parentNode.removeChild(mediaElement);
        }
 
    };
    rtcMultiConnection.onopen = function (e) {
        if (!e.extra.username) {
            e.extra.username = 'userid:' + e.userid;
        }
 
        if (e.extra.username !== session_username) {
 
            addJoinLeftRoom({
                header: e.extra.username,
                message: 'join',
                userinfo: "",
                color: e.extra.color
            }, room_id);
 
        }
 
    };
 
    rtcMultiConnection.onunmute = function (e) {
        if (e.session.audio && !e.session.video) {
            e.mediaElement.muted = false;
            return;
        }
 
        if (rtcMultiConnection.dontUnMute) {
            setTimeout(function () {
                rtcMultiConnection.onunmute(e);
            }, 1000);
            return;
        }
 
        e.mediaElement.removeAttribute('poster');
 
        setTimeout(function () {
            e.mediaElement.src = URL.createObjectURL(e.stream);
 
            setTimeout(function () {
                var isPromise = e.mediaElement.play();
                if (isPromise) {
                    rtcMultiConnection.dontMute = true;
                    isPromise.then(function () {
                        rtcMultiConnection.dontMute = false;
                    });
                }
            }, 700);
        }, 700);
    };
 
    rtcMultiConnection.onmute = function (e) {
        if (e.session.audio && !e.session.video) {
            e.mediaElement.muted = true;
            return;
        }
 
        if (rtcMultiConnection.dontMute) {
            setTimeout(function () {
                rtcMultiConnection.onmute(e);
            }, 1000);
            return;
        }
 
        e.mediaElement.src = null;
 
        setTimeout(function () {
            e.mediaElement.setAttribute('poster', 'photo.jpg');
 
            var isPromise = e.mediaElement.pause();
            if (isPromise) {
                rtcMultiConnection.dontUnMute = true;
                isPromise.then(function () {
                    rtcMultiConnection.dontUnMute = false;
                });
            }
        }, 700);
    };
    rtcMultiConnection.onclose = function () {
        if (rtcMultiConnection.getAllParticipants().length) {
            console.log('You are still connected with: ' + rtcMultiConnection.getAllParticipants().join(', '));
        } else {
            console.log('Seems session has been closed or all participants left.');
        }
    };
 
    rtcMultiConnection.onEntireSessionClosed = function (event) {
        rtcMultiConnection.attachStreams.forEach(function (stream) {
            stream.stop();
        });
        // don't display alert for moderator
        if (rtcMultiConnection.userid === event.userid)
            return;
        console.log('Entire session has been closed by the moderator: ' + event.userid);
    };
    rtcMultiConnection.onMediaError = function (e) {
        if (e.message === 'Concurrent mic process limit.') {
            if (DetectRTC.audioInputDevices.length <= 1) {
                alert('Please select external microphone. Check github issue number 483.');
                return;
            }
            var secondaryMic = DetectRTC.audioInputDevices[1].deviceId;
            rtcMultiConnection.mediaConstraints.audio = {
                deviceId: secondaryMic
            };
            rtcMultiConnection.join(rtcMultiConnection.sessionid);
        }
    };
    if (typeof webkitMediaStream !== 'undefined') {
        rtcMultiConnection.attachStreams.push(new webkitMediaStream());
    } else if (typeof MediaStream !== 'undefined') {
        rtcMultiConnection.attachStreams.push(new MediaStream());
    } else {
        console.error('Neither Chrome nor Firefox. This demo may NOT work.');
    }
 
    rtcMultiConnection.sendMessage = function (message) {
        message.userid = rtcMultiConnection.userid;
        message.extra = rtcMultiConnection.extra;
        rtcMultiConnection.sendCustomMessage(message);
    };
 
    rtcMultiConnection.DetectRTC.load(function () {
        if (rtcMultiConnection.DetectRTC.hasMicrophone === true) {
            // enable microphone
            rtcMultiConnection.mediaConstraints.audio = true;
            rtcMultiConnection.session.audio = true;
        }
 
        if (rtcMultiConnection.DetectRTC.hasWebcam === true) {
            // enable camera
            rtcMultiConnection.mediaConstraints.video = true;
            rtcMultiConnection.session.video = true;
        }
 
        if (rtcMultiConnection.DetectRTC.hasSpeakers === false) { // checking for "false"
            //alert('Please attach a speaker device. You will unable to hear the incoming audios.');
        }
    });
    return rtcMultiConnection;
}
 
//This code for start/stop streaming of user.
 
$(document).on("click", ".show-hide-user-cam", function () {
    var username = $(this).data("list-username");
    $(this).toggleClass("user-active");
    var room_id = $(this).data("room-id");
 
    var myConnection = getConnection(allConnections, room_id);
 
    var unique_identifier = $(this).data("list-unique_identifier");
    unique_identifier = unique_identifier.split("_");
    if ($("#chat-tab-" + room_id + " .show-hide-user-cam.user-active").length) {
        $("#chat-tab-" + room_id + " .activity-message").removeClass("height-409").addClass("height-259");
        $("#chat-tab-" + room_id + " .video-carousel").removeClass("hide");
    } else {
        $("#chat-tab-" + room_id + " .activity-message").removeClass("height-259").addClass("height-409");
        $("#chat-tab-" + room_id + " .video-carousel").addClass("hide");
    }
    $("#chat-tab-" + room_id + " .usercam_" + username).not("#my-webcam-container-" + room_id + " .usercam_" + username).toggleClass("hide");
    $("#my-webcam-container-" + room_id + " .usercam_" + username).toggleClass("hide");
    var streamId = $("#chat-tab-" + room_id + " .usercam_" + username).attr("id");
   
    if (CommonFunctions.getLocalStorage("is_room_streamed_" + room_id) == 0) {
        myConnection.addStream({
            audio: true,
            video: true
        });
        CommonFunctions.setLocalStorage("is_room_streamed_" + room_id, 1);
    } else {
        if ($(this).hasClass("user-active")) {
            myConnection.attachStreams.forEach(function (stream) {
                if (stream.id == streamId) {
                    stream.unmute('audio');
                }
            });
        } else {
            myConnection.attachStreams.forEach(function (stream) {
                if (stream.id == streamId) {
                    stream.mute('audio');
                }
            });
        }
    }
});

Please help for find the solution for this feature.

Waiting for your reply @muaz-khan

imail2pankaj avatar Mar 21 '18 12:03 imail2pankaj

What I did was using partial views for calling the view of video on request (using MVC 5), but of course, that's not really a solution to this question, just a quick fix that I needed. I hope you get an answer, I'm also interested in video call on user demand.

Jhordan92 avatar May 23 '18 13:05 Jhordan92

Hi @muaz-khan , I also want to achieve the same functionality, Please let us know how to achieve it,

ashishnaghate avatar Feb 04 '19 06:02 ashishnaghate

I have done this feature,

// get stream by streamID var stream = connection.streamEvents[streamid].stream; // this is for video mute/unmute connection.attachStreams.forEach(function(stream) { stream.getVideoTracks().forEach( t => t.enabled = !t.enabled );
});

// this is audio mute/unmute connection.attachStreams.forEach(function(stream) { stream.getAudioTracks().forEach( t => t.enabled = !t.enabled );
});

this is worked for me, Thank You

AnilKumarBoddu avatar Apr 24 '19 11:04 AnilKumarBoddu

Hello @muaz-khan , I am working on a Project of group chat and it is working fine but sometimes streaming is not happening.

I am start streaming on joining of the room, so when any user joins the room streaming will start automatically, but I don't want to do that. I am creating list of users who joined the room and each user have camera icon beside the name in the list. By clicking on that camera icon want to stream for particular user. So if I have started streaming then all the users who joined the room will be able to see my cam. If they click on camera icon beside his name to start streaming then other users should be able to view his cam including me. If again he click on camera icon to disable camera then all the users will not be able to view his cam. Check below screenshot for more explanation.

chrome-edit

By default current user's camera icon will be visible. All the other user's camera icon will be hidden. Cam will be visible on the start of the streaming.

I have tried using below code, but only my cam start streaming not able to view cam on peer side.

myConnection.addStream({
    audio: true,
    video: true
});

ui.main.js You can get code from this link

var allConnections = new Array();

setInterval(CommonFunctions.joinedRoomUserCount, 300000);

var rtcMultiConnection = new RTCMultiConnection();
var summerNoteOptions = summernoteSettings();

var usersContainer = getElement('.users-container');

function getElement(selector) {
    return document.querySelector(selector);
}

function leaveRoomFromSession(room_id) {

    var store_message = CommonFunctions.setRoomLeftMessage($("#user_id").val());
    CommonFunctions.sendMessageAjax(room_id, $("#user_id").val(), $(store_message).html());

    CommonFunctions.setLocalStorage("is_room_streamed_" + room_id, 0);

    CommonFunctions.joinedRoomUserCount();

    var customEvent = {message: "room-counter", totalUsers: rtcMultiConnection.getAllParticipants().length, room_id: room_id};
    connectionSocket.socket.emit('room-count-users', customEvent);


    if (typeof rtcMultiConnection.attachStreams === "undefined") {
    } else {
        rtcMultiConnection.attachStreams.forEach(function (localStream) {
            var streamId = localStream.streamid;
            if (typeof streamId !== "undefined") {
                streamId = streamId.replace("{", "");
                streamId = streamId.replace("}", "");
                $('#' + streamId).parents(".item").remove();
                $('#' + streamId).remove();
            }
            localStream.stop();
        });
        rtcMultiConnection.leave();
    }
}
var main = getElement('.main');

$(document).on("click", '.continue', function (e) {
    // This line will start room session. user can join with this event
    e.preventDefault();

    var room_status = $(this).html();
    $(this).prop("disabled", true);
    $(this).html("Enter");
    $(this).tab('show');
    var yourName = main.querySelector('#your-name');
    var roomName = $(this).attr('data-room');

    var user_id = $("#user_id").val();

    if (!roomName) {
        roomName.focus();
        return alert('Your MUST Enter Room Name!');
    }

    localStorage.setItem('room-name', roomName);
    localStorage.setItem('user-name', yourName.value);

    var username = yourName.value || 'Anonymous';
    var myunique_identifier = username + "_" + role.toLowerCase() + "_" + user_id;

    rtcMultiConnection = initializeCon(room_id);

    rtcMultiConnection.extra.user_id = user_id;
    rtcMultiConnection.extra.username = username;
    rtcMultiConnection.extra.role = role.toLowerCase();
    rtcMultiConnection.extra.unique_identifier = myunique_identifier;
    rtcMultiConnection.extra.color = getRandomColor();
    var roomid = CommonFunctions.slug(roomName);
    rtcMultiConnection.channel = roomid;
    rtcMultiConnection.userid = myunique_identifier;
    rtcMultiConnection.sessionid = roomid;

    var userkey = CommonFunctions.userKeyString() + user_id;
    rtcMultiConnection.extra.userkey = userkey;

    setTimeout(function () {
        $(".chat-room").animate({
            scrollTop: $('.chat-room')[0].scrollHeight - $('.chat-room')[0].clientHeight
        }, 100);
    }, 2000);

    rtcMultiConnection.checkPresence(roomid, function (isRoomExists) {
        participantType = 0;
        if (!isRoomExists) {
            rtcMultiConnection.open(roomid);
        } else {
            addJoinLeftRoom({
                header: username,
                message: ' joined',
                userinfo: '<img src="images/action-needed.png">'
            }, room_id);
            rtcMultiConnection.join(roomid);
            participantType = 1;
        }
        joinRoom(room_id, user_id, participantType);
        var store_message = CommonFunctions.setRoomLeftMessage(username);

        var socket = rtcMultiConnection.getSocket();
        socket.on(rtcMultiConnection.socketCustomEvent, rtcMultiConnection.onCustomMessage);

        console.debug('room is present?', isRoomExists);
    });

    CommonFunctions.setLocalStorage("is_room_streamed_" + room_id, 0);
    allConnections.push({room_id: room_id, connection: rtcMultiConnection});
});


function getConnection(allConnections, room_id) {
    var connection = {};
    if (allConnections.length) {
        for (var cnt = 0; cnt < allConnections.length; cnt++) {
            if (allConnections[cnt].room_id = room_id) {
                return allConnections[cnt].connection;
            }
        }
    }
    return connection;
}


var isShiftKeyPressed = false;
var numberOfKeys = 0;
function userIsTyping(e, room_id) {

    if (e.keyCode == 16) {
        isShiftKeyPressed = true;
    }

    numberOfKeys++;
    if (numberOfKeys > 3)
        numberOfKeys = 0;

    if (!numberOfKeys) {
        if (e.keyCode == 8) {
            return rtcMultiConnection.send({
                stoppedTyping: true
            });
        }

        rtcMultiConnection.send({
            typing: true
        });
    }

    if (isShiftKeyPressed) {
        if (e.keyCode == 16) {
            isShiftKeyPressed = false;
        }
        return;
    }

    if (e.keyCode == 13 && !e.shiftKey) {
        sendChatMessage(room_id, 0);
    }
}

ui.peer-connection.js You can get code from this link


//Created function for initialize rtcmulticonnection.
function initializeCon(room_id) {
 
    window.enableAdapter = true; // enable adapter.js
    var rtcMultiConnection = new RTCMultiConnection();
    rtcMultiConnection.autoCreateMediaElement = false;
    rtcMultiConnection.dontCaptureUserMedia = true;
 
    rtcMultiConnection.socketMessageEvent = 'private-chat-demo';
 
    rtcMultiConnection.customStreams = {};
    rtcMultiConnection.renegotiatedSessions = {};
 
    rtcMultiConnection.session = {
        audio: false,
        video: false,
        data: true
    };
 
    var BandwidthHandler = rtcMultiConnection.BandwidthHandler;
    rtcMultiConnection.bandwidth = {
        audio: 50,
        video: 200,
        screen: 200
    };
 
    rtcMultiConnection.mediaConstraints = {
        video: false,
        audio: false
    };
 
    rtcMultiConnection.userid = session_username;
 
    rtcMultiConnection.extra = {
        username: session_username
    }
 
    rtcMultiConnection.optionalArgument = null;
 
    rtcMultiConnection.sdpConstraints.mandatory = {
        OfferToReceiveAudio: true,
        OfferToReceiveVideo: true
    };
 
    rtcMultiConnection.videosContainer = document.getElementById('videos-container-' + room_id);
 
    rtcMultiConnection.onstream = function (event) {
        event.mediaElement.removeAttribute('src');
        event.mediaElement.removeAttribute('srcObject');
 
        var video = document.createElement('video');
        video.controls = true;
        video.muted = true;
        if (event.type === 'local') {
            video.muted = true;
        }
        video.srcObject = event.stream;
 
        var width = 200;
        var mediaElement = getHTMLMediaElement(video, {
            title: event.extra.username,
            width: width,
            showOnMouseEnter: false,
            initiator: event.extra.username != session_username ? "hide" : "",
            streamId: event.streamid
        });
 
        if (event.extra.username == session_username) {
            var myVideosContainer = document.getElementById('my-webcam-container-' + room_id);
            myVideosContainer.appendChild(mediaElement);
 
            $("#my-webcam-container-" + room_id + " .usercam_" + event.extra.username).removeClass("hide");
            $(".room-" + room_id + "-mt-comment#online-user-items-" + event.extra.username + " a").addClass("user-active");
        } else {
            rtcMultiConnection.videosContainer.appendChild(mediaElement);
        }
        if (event.type === 'remote') {
            rtcMultiConnection.attachStreams.forEach(function (stream) {
                if (typeof stream.mute == "function") {
                    stream.mute("audio"); // mute all tracks
                }
            });
        }
        mediaElement.media.play();
        mediaElement.id = event.streamid;
 
    };
 
    rtcMultiConnection.onleave = function (event) {
        if (event.extra.username) {
            addJoinLeftRoom({
                header: event.extra.username,
                message: 'left',
                userinfo: "",
                color: event.extra.color
            }, room_id);
        }
 
    };
 
    var whoIsTyping = document.querySelector('#who-is-typing' + room_id);
    rtcMultiConnection.onmessage = function (e) {
 
        if (e.data.typing) {
            whoIsTyping.innerHTML = e.extra.username + ' is typing ...';
            return;
        }
        if (e.data.stoppedTyping) {
            whoIsTyping.innerHTML = '';
            return;
        }
 
        whoIsTyping.innerHTML = '';
        var isWhisper = false;
        var message = e.data;
        var whisperUser = "";
        if (e.data.indexOf("send-whisper-") > 0) {
            whisperUser = $(message, "span.whisper-message").html();
            isWhisper = true;
 
        }
        if (isWhisper && whisperUser == session_username) {
            addNewMessage({
                header: e.extra.username,
                message: ' ' + e.data,
                userinfo: "",
                color: e.extra.color
            }, room_id);
        } else if (!isWhisper && whisperUser === "") {
            addNewMessage({
                header: e.extra.username,
                message: ' ' + e.data,
                userinfo: "",
                color: e.extra.color
            }, room_id);
        }
    };
 
    rtcMultiConnection.onstreamended = function (event) {
        var mediaElement = document.getElementById(event.streamid);
        if (mediaElement) {
            mediaElement.parentNode.removeChild(mediaElement);
        }
 
    };
    rtcMultiConnection.onopen = function (e) {
        if (!e.extra.username) {
            e.extra.username = 'userid:' + e.userid;
        }
 
        if (e.extra.username !== session_username) {
 
            addJoinLeftRoom({
                header: e.extra.username,
                message: 'join',
                userinfo: "",
                color: e.extra.color
            }, room_id);
 
        }
 
    };
 
    rtcMultiConnection.onunmute = function (e) {
        if (e.session.audio && !e.session.video) {
            e.mediaElement.muted = false;
            return;
        }
 
        if (rtcMultiConnection.dontUnMute) {
            setTimeout(function () {
                rtcMultiConnection.onunmute(e);
            }, 1000);
            return;
        }
 
        e.mediaElement.removeAttribute('poster');
 
        setTimeout(function () {
            e.mediaElement.src = URL.createObjectURL(e.stream);
 
            setTimeout(function () {
                var isPromise = e.mediaElement.play();
                if (isPromise) {
                    rtcMultiConnection.dontMute = true;
                    isPromise.then(function () {
                        rtcMultiConnection.dontMute = false;
                    });
                }
            }, 700);
        }, 700);
    };
 
    rtcMultiConnection.onmute = function (e) {
        if (e.session.audio && !e.session.video) {
            e.mediaElement.muted = true;
            return;
        }
 
        if (rtcMultiConnection.dontMute) {
            setTimeout(function () {
                rtcMultiConnection.onmute(e);
            }, 1000);
            return;
        }
 
        e.mediaElement.src = null;
 
        setTimeout(function () {
            e.mediaElement.setAttribute('poster', 'photo.jpg');
 
            var isPromise = e.mediaElement.pause();
            if (isPromise) {
                rtcMultiConnection.dontUnMute = true;
                isPromise.then(function () {
                    rtcMultiConnection.dontUnMute = false;
                });
            }
        }, 700);
    };
    rtcMultiConnection.onclose = function () {
        if (rtcMultiConnection.getAllParticipants().length) {
            console.log('You are still connected with: ' + rtcMultiConnection.getAllParticipants().join(', '));
        } else {
            console.log('Seems session has been closed or all participants left.');
        }
    };
 
    rtcMultiConnection.onEntireSessionClosed = function (event) {
        rtcMultiConnection.attachStreams.forEach(function (stream) {
            stream.stop();
        });
        // don't display alert for moderator
        if (rtcMultiConnection.userid === event.userid)
            return;
        console.log('Entire session has been closed by the moderator: ' + event.userid);
    };
    rtcMultiConnection.onMediaError = function (e) {
        if (e.message === 'Concurrent mic process limit.') {
            if (DetectRTC.audioInputDevices.length <= 1) {
                alert('Please select external microphone. Check github issue number 483.');
                return;
            }
            var secondaryMic = DetectRTC.audioInputDevices[1].deviceId;
            rtcMultiConnection.mediaConstraints.audio = {
                deviceId: secondaryMic
            };
            rtcMultiConnection.join(rtcMultiConnection.sessionid);
        }
    };
    if (typeof webkitMediaStream !== 'undefined') {
        rtcMultiConnection.attachStreams.push(new webkitMediaStream());
    } else if (typeof MediaStream !== 'undefined') {
        rtcMultiConnection.attachStreams.push(new MediaStream());
    } else {
        console.error('Neither Chrome nor Firefox. This demo may NOT work.');
    }
 
    rtcMultiConnection.sendMessage = function (message) {
        message.userid = rtcMultiConnection.userid;
        message.extra = rtcMultiConnection.extra;
        rtcMultiConnection.sendCustomMessage(message);
    };
 
    rtcMultiConnection.DetectRTC.load(function () {
        if (rtcMultiConnection.DetectRTC.hasMicrophone === true) {
            // enable microphone
            rtcMultiConnection.mediaConstraints.audio = true;
            rtcMultiConnection.session.audio = true;
        }
 
        if (rtcMultiConnection.DetectRTC.hasWebcam === true) {
            // enable camera
            rtcMultiConnection.mediaConstraints.video = true;
            rtcMultiConnection.session.video = true;
        }
 
        if (rtcMultiConnection.DetectRTC.hasSpeakers === false) { // checking for "false"
            //alert('Please attach a speaker device. You will unable to hear the incoming audios.');
        }
    });
    return rtcMultiConnection;
}
 
//This code for start/stop streaming of user.
 
$(document).on("click", ".show-hide-user-cam", function () {
    var username = $(this).data("list-username");
    $(this).toggleClass("user-active");
    var room_id = $(this).data("room-id");
 
    var myConnection = getConnection(allConnections, room_id);
 
    var unique_identifier = $(this).data("list-unique_identifier");
    unique_identifier = unique_identifier.split("_");
    if ($("#chat-tab-" + room_id + " .show-hide-user-cam.user-active").length) {
        $("#chat-tab-" + room_id + " .activity-message").removeClass("height-409").addClass("height-259");
        $("#chat-tab-" + room_id + " .video-carousel").removeClass("hide");
    } else {
        $("#chat-tab-" + room_id + " .activity-message").removeClass("height-259").addClass("height-409");
        $("#chat-tab-" + room_id + " .video-carousel").addClass("hide");
    }
    $("#chat-tab-" + room_id + " .usercam_" + username).not("#my-webcam-container-" + room_id + " .usercam_" + username).toggleClass("hide");
    $("#my-webcam-container-" + room_id + " .usercam_" + username).toggleClass("hide");
    var streamId = $("#chat-tab-" + room_id + " .usercam_" + username).attr("id");
   
    if (CommonFunctions.getLocalStorage("is_room_streamed_" + room_id) == 0) {
        myConnection.addStream({
            audio: true,
            video: true
        });
        CommonFunctions.setLocalStorage("is_room_streamed_" + room_id, 1);
    } else {
        if ($(this).hasClass("user-active")) {
            myConnection.attachStreams.forEach(function (stream) {
                if (stream.id == streamId) {
                    stream.unmute('audio');
                }
            });
        } else {
            myConnection.attachStreams.forEach(function (stream) {
                if (stream.id == streamId) {
                    stream.mute('audio');
                }
            });
        }
    }
});

Please help for find the solution for this feature.

Waiting for your reply @muaz-khan

Hello Pankaj, Di you finished your chat with these Functions? if so please let me see the demo.

easyrahil avatar Jan 31 '22 13:01 easyrahil

@easyrahil that project dropped a long time ago

imail2pankaj avatar Jan 31 '22 14:01 imail2pankaj

But Pankaj that was a good project needs to improve timely. did you succeed already? i wanna try it somehow. as it has different rooms and userlist. with webcam

easyrahil avatar Jan 31 '22 15:01 easyrahil