WebRtc 屏幕共享

作者: HeloWxl | 来源:发表于2022-06-10 11:32 被阅读0次

    效果图

    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;
            }
    
        }
    

    相关文章

      网友评论

        本文标题:WebRtc 屏幕共享

        本文链接:https://www.haomeiwen.com/subject/otommrtx.html