tiny
tiny

Reputation: 151

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?

Upvotes: 2

Views: 976

Answers (1)

ishan shah
ishan shah

Reputation: 603

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

Upvotes: 0

Related Questions