简体   繁体   中英

Screen sharing using webRTC when audio call in javascript

I am going to make screen sharing function using webRTC. My code is working well when video calling But in audio call status, that is not working. Here is my code.

This is for create peer Connection and add stream for audio calling

const senders = [];
var mediaConstraints = {audio: true, video: false}
navigator.mediaDevices.getUserMedia(mediaConstraints)
    .then(function (localStream) {
        localLiveStream = localStream;
        document.getElementById("local_video").srcObject = localLiveStream;
        localLiveStream.getTracks().forEach(track => senders.push(myPeerConnection.addTrack(track, localLiveStream)));
            })
    .catch(handleGetUserMediaError);

when screen share field

mediaConstraints.video = true;
let displayStream = await navigator.mediaDevices.getDisplayMedia(mediaConstraints)
if (displayStream) {
    document.getElementById("local_video").srcObject = displayStream;
    console.log("senders: ", senders);
    try {
        senders.find(sender => sender.track.kind === 'video').replaceTrack(displayStream.getTracks()[0]);
    } catch (e) {
        console.log("Error: ", e)
    }
}

In screen sharing status, sender.track.kind is "audio" So

senders.find(sender => sender.track.kind === 'video') = null.

As this, replaceTrack makes error is there any other way for screen share?

You need to add a video track in order to achieve this. It will require renegotiation.

So add the screen track (not replace) to the connection and then create the offer again!

connection.addTrack(screenVideoTrack);

Check this for reference:

https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/onnegotiationneeded

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM