天天看點

聲網實作螢幕共享以及直播

最近因為公司新增需求是以花費了2周時間搞定 中途出現許許多多的問題 在網上實在沒有找到類似的資料 是以才發一張文章

注:我這邊實作的學生可以申請一對一的視訊通話 通過websocket儲存key并且推送給老師或者學生

var client, localStream, camera, microphone;

var screenClient, screenStream;

var videoClient, videoStream;

var cameraUid = “”;

var strCameraUid = “”;

var screenUid = “”;

var audioSelect = document.querySelector(‘select#audioSource’);

var videoSelect = document.querySelector(‘select#videoSource’);

//老師攝像頭

function teaJoin() {

var channel_key = null;

client = AgoraRTC.createClient({mode: ‘rtc’, codec: ‘vp8’});

client.init(key.value, function () {

client.join(channel_key, courseId, null, function (uid) {

camera = videoSource.value;

microphone = audioSource.value;

localStream = AgoraRTC.createStream({

streamID: uid,

audio: true,

cameraId: camera,

microphoneId: microphone,

video: true,

screen: false

});

localStream.setVideoProfile(‘720p_3’);

if(userRole ==“T”){

cameraUid = uid;

}else{

strCameraUid = uid;

}

// The user has granted access to the camera and mic.

localStream.on(“accessAllowed”, function () {

console.log(“accessAllowed”);

});

// The user has denied access to the camera and mic.
            localStream.on("accessDenied", function () {
                console.log("accessDenied");
            });

            localStream.init(function () {
                console.log("getUserMedia successfully");
                if(userRole == "T"){
                    $('#playDiv').html('');
                    localStream.play('playDiv');
                }else{
                    $('#small_playDiv').html('');
                    localStream.play('small_playDiv');
                }
                // localStream.play('agora_video_local');

                client.publish(localStream, function (err) {
                    console.log("Publish local stream error: " + err);
                });

                client.on('stream-published', function (evt) {
                    console.log("Publish local stream successfully");
                    if(userRole =="T"){
                        canPlay(cameraUid);
                        var btn = $("#startPlayBtn");
                        btn.attr("onclick","teaUnpublish()");
                        btn.removeAttr("disabled");
                        btn.css("background-color", "red");
                        btn.val("結束視訊");
                    }
                });
            }, function (err) {
                console.log("getUserMedia failed", err);
            });

    }, function (err) {
        console.log("Join channel failed", err);
    });
}, function (err) {
    console.log("AgoraRTC client init failed", err);
});

channelKey = "";
client.on('error', function (err) {
    console.log("Got error msg:", err.reason);
    if (err.reason === 'DYNAMIC_KEY_TIMEOUT') {
        client.renewChannelKey(channelKey, function () {
            console.log("Renew channel key successfully");
        }, function (err) {
            console.log("Renew channel key failed: ", err);
        });
    }
});

client.on('stream-removed', function (evt) {
    var stream = evt.stream;
    stream.stop();
    $('#agora_remote' + stream.getId()).remove();
    console.log("Remote stream is removed " + stream.getId());
});

client.on('peer-leave', function (evt) {
    var stream = evt.stream;
    if (stream) {
        stream.stop();
        $('#agora_remote' + stream.getId()).remove();
        console.log(evt.uid + " leaved from this channel");
    }
});
           

}

//學生攝像頭

function stJoin() {

var channel_key = null;

videoClient = AgoraRTC.createClient({mode: ‘rtc’, codec: ‘vp8’});

videoClient.init(key.value, function () {

videoClient.join(channel_key, courseId, null, function (uid) {

camera = videoSource.value;

microphone = audioSource.value;

videoStream = AgoraRTC.createStream({

streamID: uid,

audio: true,

cameraId: camera,

microphoneId: microphone,

video: true,

screen: false

});

videoStream.setVideoProfile(‘720p_3’);

strCameraUid = uid;

// The user has granted access to the camera and mic.

videoStream.on(“accessAllowed”, function () {

console.log(“accessAllowed”);

});

// The user has denied access to the camera and mic.
        videoStream.on("accessDenied", function () {
            console.log("accessDenied");
        });

        videoStream.init(function () {
            console.log("getUserMedia successfully");
                $('#small_playDiv').html('');
                videoStream.play('small_playDiv');
            // localStream.play('agora_video_local');

            videoClient.publish(videoStream, function (err) {
                console.log("Publish local stream error: " + err);
            });

            videoClient.on('stream-published', function (evt) {
                console.log("Publish local stream successfully");
            });
        }, function (err) {
            console.log("getUserMedia failed", err);
        });

    }, function (err) {
        console.log("Join channel failed", err);
    });
}, function (err) {
    console.log("AgoraRTC client init failed", err);
});

channelKey = "";
videoClient.on('error', function (err) {
    console.log("Got error msg:", err.reason);
    if (err.reason === 'DYNAMIC_KEY_TIMEOUT') {
        videoClient.renewChannelKey(channelKey, function () {
            console.log("Renew channel key successfully");
        }, function (err) {
            console.log("Renew channel key failed: ", err);
        });
    }
});

videoClient.on('stream-removed', function (evt) {
    var stream = evt.stream;
    stream.stop();
    $('#agora_remote' + stream.getId()).remove();
    console.log("Remote stream is removed " + stream.getId());
});

videoClient.on('peer-leave', function (evt) {
    var stream = evt.stream;
    if (stream) {
        stream.stop();
        $('#agora_remote' + stream.getId()).remove();
        console.log(evt.uid + " leaved from this channel");
    }
});
           

}

//螢幕共享

function joinStr(cheID) {

var channel_key = null;

screenClient = AgoraRTC.createClient({mode: ‘rtc’, codec: ‘vp8’});

screenClient.init(key.value, function () {

screenClient.join(channel_key, courseId, null, function(uid) {

screenUid = uid;

screenStream = AgoraRTC.createStream({

streamID: uid,

audio: false,

video: false,

screen: true,

//chrome extension ID

extensionId: cheID

});

screenStream.setVideoProfile(‘720p_3’);

// The user has granted access to the camera and mic.

screenStream.on(“accessAllowed”, function() {

console.log(“accessAllowed”);

});

// The user has denied access to the camera and mic.
            screenStream.on("accessDenied", function() {
                console.log("accessDenied");
            });

            screenStream.init(function() {
                screenStream.play('agora_local2');
                $("#video").css("display","block");
                $("#container").css("display","none");

                screenClient.publish(screenStream, function (err) {
                    console.log("Publish local screenstream error: " + err);
                });

                screenClient.on('stream-published', function (evt) {
                    screenPlay(screenUid);
                    var btn = $("#screenShare");
                    btn.attr("onclick","strUnpublish()");
                    btn.removeAttr("disabled");
                    btn.css("background-color", "#0e5a94");
                    $("#screenShare span").html("關閉螢幕");
                });
            }, function (err) {
                alert("請輸入正确的共享螢幕插件ID");
                CHROME_ID = "";
                console.log("getUserMedia failed", err);
            });

    }, function(err) {
        console.log("Join channel failed", err);
    });
}, function (err) {
    console.log("AgoraRTC client init failed", err);
});

channelKey = "";
screenClient.on('error', function(err) {
    console.log("Got error msg:", err.reason);
    if (err.reason === 'DYNAMIC_KEY_TIMEOUT') {
        screenClient.renewChannelKey(channelKey, function(){
            console.log("Renew channel key successfully");
        }, function(err){
            console.log("Renew channel key failed: ", err);
        });
    }
});

screenClient.on('stream-removed', function (evt) {
    var stream = evt.stream;
    stream.stop();
    $('#agora_remote' + stream.getId()).remove();
    console.log("Remote stream is removed " + stream.getId());

});

screenClient.on('peer-leave', function (evt) {
    var stream = evt.stream;
    if (stream) {
        stream.stop();
        $('#agora_remote' + stream.getId()).remove();
        console.log(evt.uid + " leaved from this channel");
    }
});
           

}

function leave() {

// document.getElementById(“leave”).disabled = true;

client.leave(function () {

console.log(“Leavel channel successfully”);

}, function (err) {

console.log(“Leave channel failed”);

});

}

function publish() {

// document.getElementById(“publish”).disabled = true;

// document.getElementById(“unpublish”).disabled = false;

client.publish(localStream, function (err) {

console.log("Publish local stream error: " + err);

});

}

//關閉老師攝像頭

function teaUnpublish() {

if (localStream != null) {

localStream.stop();

localStream.close()

client.unpublish(localStream, function(err) {

console.log(“Unpublish local stream failed” + err);

});

var btn = $("#startPlayBtn");

btn.attr(“onclick”,“teaJoin()”);

btn.css(“background-color”, “#338FCC”);

btn.val(“開始視訊”);

localStream = null;

}

}

//關閉螢幕共享

function strUnpublish() {

if (screenStream != null) {

screenStream.stop();

screenStream.close()

client.unpublish(screenStream, function(err) {

console.log(“Unpublish local stream failed” + err);

});

var btn = $("#screenShare");

btn.attr(“onclick”,“verification()”);

btn.css(“background-color”, “#0e6eb8”);

$("#screenShare span").html(“螢幕共享”);

$("#video").css(“display”,“none”);

$("#container").css(“display”,“block”);

screenStream = null;

}

}

//關閉學生攝像頭

function stUnpublish() {

if (videoStream != null) {

videoStream.stop();

videoStream.close()

client.unpublish(videoStream, function(err) {

console.log(“Unpublish local stream failed” + err);

});

videoStream = null;

}

}

function getDevices() {

AgoraRTC.getDevices(function (devices) {

for (var i = 0; i !== devices.length; ++i) {

var device = devices[i];

var option = document.createElement(‘option’);

option.value = device.deviceId;

if (device.kind === ‘audioinput’) {

option.text = device.label || 'microphone ’ + (audioSelect.length + 1);

audioSelect.appendChild(option);

} else if (device.kind === ‘videoinput’) {

option.text = device.label || 'camera ’ + (videoSelect.length + 1);

videoSelect.appendChild(option);

} else {

console.log('Some other kind of source/device: ', device);

}

}

});

}

getDevices();

//學生

function stuJoin() {

var channel_key = null;

client = AgoraRTC.createClient({mode: ‘rtc’, codec: ‘vp8’});

client.init(key.value, function () {

console.log(“AgoraRTC client initialized”);

client.join(channel_key, courseId, null, function (uid) {

console.log(“User " + uid + " join channel successfully”);

}, function (err) {
        console.log("Join channel failed", err);
    });
}, function (err) {
    console.log("AgoraRTC client init failed", err);
});

channelKey = "";
client.on('error', function (err) {
    console.log("Got error msg:", err.reason);
    if (err.reason === 'DYNAMIC_KEY_TIMEOUT') {
        client.renewChannelKey(channelKey, function () {
            console.log("Renew channel key successfully");
        }, function (err) {
            console.log("Renew channel key failed: ", err);
        });
    }
});


client.on('stream-added', function (evt) {
    var stream = evt.stream;
    client.subscribe(stream, function (err) {
        console.log("Subscribe stream failed", err);
    });
});

client.on('stream-subscribed', function (evt) {
    var stream = evt.stream;
    var cameraId = $("#cameraId").html();
    var screenId = $("#screenId").html();
    //老師端攝像頭
    //如果是老師,先打開小播放區,否則先打開大播放區
    if(stream.getId() !=cameraId && stream.getId() !=screenId){
            if ($('#playDiv').html() == "") {
                $('#playDiv').append('<div id="agora_remote5' + stream.getId() + '" style="float:left; width:100%;height:100%;display:inline-block;"></div>');
                stream.play('agora_remote5' + stream.getId());
            }else{
                $('#small_playDiv').html("");
                $('#small_playDiv').append('<div id="agora_remote5' + stream.getId() + '" style="float:left; width:100%;height:100%;display:inline-block;"></div>');
                stream.play('agora_remote5' + stream.getId());
            }
    }
    //學生端攝像頭
    if(stream.getId() == cameraId){
        if (userRole != "Z") {
            if (userRole != "T") {//如果是老師,先打開小播放區,否則先打開大播放區
                if ($('#playDiv').html() == "") {
                    $('#playDiv').append('<div id="agora_remote' + stream.getId() + '" style="float:left; width:100%;height:100%;display:inline-block;"></div>');
                    stream.play('agora_remote' + stream.getId());
                } else if ($('#small_playDiv').html() == "") {
                    $('#small_playDiv').append('<div id="agora_remote' + stream.getId() + '" style="float:left; width:100%;height:100%;display:inline-block;"></div>');
                    stream.play('agora_remote' + stream.getId());
                }
            }
        }
    }
    //共享螢幕
    if(stream.getId() == screenId && userRole != "T"){
        $("#video").css("display","block");
        $("#agora_local2").css("display","none");
        $("#container").css("display","none");
        $("#applyBoardBtn").css("display","none");
        if ($('div#video #agora_remote' + stream.getId()).length === 0) {
            $('div#video').append('<div id="agora_remote' + stream.getId() + '" style="float:right; width:100%;height:100%;display:inline-block;"></div>');
        }
        stream.play('agora_remote' + stream.getId());
    }

});

client.on('stream-removed', function (evt) {
    var stream = evt.stream;
    stream.stop();
    $('#agora_remote' + stream.getId()).remove();
    if(userRole == "S"){
        if(stream.getId() == $("#screenId").html()){
            $("#applyBoardBtn").css("display","block");
            $("#container").css("display","block");
            $("#video").css("display","none");
        }
    }

    console.log("Remote stream is removed " + stream.getId());
});

client.on('peer-leave', function (evt) {
    var stream = evt.stream;
    if (stream) {
        stream.stop();
        $('#agora_remote' + stream.getId()).remove();
        console.log(evt.uid + " leaved from this channel");
    }
});
           

}