音视频通话

WebRtc 屏幕共享

2022-06-10  本文已影响0人  HeloWxl

效果图

image.png

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>屏幕共享</title>
</head>
<body>
<div id="container">
    <video id="video-local" autoplay playsinline></video>
    <button id="showVideo" onclick="startShard()">开始共享屏幕</button>
</div>
</body>
</html>

核心代码:

const constraints = window.constraints = {
        audio: true,
        video: true
    };

    async function startShard() {
        if(window.stream!=null){
            alert('你已开启屏幕共享,请勿重复打开哦');
            return false;
        }
        try {
             await navigator.mediaDevices.getDisplayMedia(constraints).then(gotStream);
        } catch (err) {
            console.error(err)
        }
    }

    function gotStream(stream) {
        const videoEle = document.querySelector('video');
        window.stream = stream;
        videoEle.srcObject = stream;

        //监听手动点击“停止分享”
        stream.getVideoTracks()[0].onended = ()=>{
            //监听以后的处理逻辑……
            alert('屏幕共享已关闭')
            videoEle.srcObject = null;
        }

    }
上一篇下一篇

猜你喜欢

热点阅读