WebRTC API to get local desktop data

1. getDisplayMedia

        WebRTC provides mediaDevices.getDisplayMedia API to obtain local desktop data, for example, we need to send the local desktop to the other party when sharing the screen.

        var promise = navigator.mediaDevices.getDisplayMedia(constraints);

        After calling this function, a pop-up window will prompt to select the screen or window you want to share (for example, if you have a dual-monitor screen locally, you can choose one of the screens, or choose the application window you want to share). After the function is called successfully, a Promise object will be returned. Receive a MediaStream object.

        constraints is a MediaStreamConstraints object whose structure is shown below.

dictionary MediaStreamConstraints {
    (boolean or MediaTrackConstraints) video = false;
    (boolean or MediaTrackConstraints) audio = false;
}

        The usage of getDisplayMedia and getUserMedia is basically the same, except that the former obtains local desktop data, while the latter obtains data from audio and video equipment, and the constraints of getDisplayMedia are consistent with those of getUserMedia.

2. Example demonstration

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>WebRTC获取本地桌面数据</title>
    </head>
    <body>
        <video autoplay playsinline id="video_player"></video>
        <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
        <script src="./js/get_desktop.js"></script>
    </body>
</html>
'use strict'

var videoPlayer = document.querySelector("video#video_player");

function HandleError(err) {
    console.log(err.name + "," + err.message);
}

function GetMediaStream(mediaStream) {
    videoPlayer.srcObject = mediaStream;
}

if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
    console.log('getDisplayMedia is not supported!');
} else {
    var constraints = {
        video : {
            frameRate   : 24,
            width       : 640,
            height      : 480
        },
        audio : {
            echoCancellation : true,
            noiseSuppression : true,
            autoGainControl  : true
        }
    };
    navigator.mediaDevices.getDisplayMedia(constraints)
        .then(GetMediaStream)
        .catch(HandleError);
}

        The effect after running is as follows. First, a pop-up prompts you to select the screen or window you want to share. After clicking Share, you can view the data of the corresponding window locally. If you want to stop obtaining desktop data, you can click Stop Sharing.

Guess you like

Origin blog.csdn.net/weixin_38102771/article/details/123616177