I've got webRTC to work on my express server but I want to be able to add the stream of the user dynamically. I looked up in the simple-peer docs and found this:
var Peer = require('simple-peer') // create peer without waiting for media
var peer1 = new Peer({ initiator: true }) // you don't need streams here
var peer2 = new Peer()
peer1.on('signal', data => {
peer2.signal(data)
})
peer2.on('signal', data => {
peer1.signal(data)
})
peer2.on('stream', stream => {
// got remote video stream, now let's show it in a video tag
var video = document.querySelector('video')
if ('srcObject' in video) {
video.srcObject = stream
} else {
video.src = window.URL.createObjectURL(stream) // for older browsers
}
video.play()
})
function addMedia (stream) {
peer1.addStream(stream) // <- add streams to peer dynamically
}
// then, anytime later...
navigator.mediaDevices.getUserMedia({
video: true,
audio: true
}).then(addMedia).catch(() => {})
Peer1 sends a stream to Peer2 dynamically, but it's in the same browser. I'm using socket.io so that people are able to join different rooms. I was using this example to get me started: https://github.com/Dirvann/webrtc-video-conference-simple-peer.
If I use the github example above I understand that I'd have to put:
navigator.mediaDevices.getUserMedia(constraints).then(stream => {
console.log('Received local stream');
localVideo.srcObject = stream;
localStream = stream;
}).catch(e => alert(`getusermedia error ${e.name}`))
In a function. Call init(); then call that function later. But in the simple-peer example it called addMedia(stream) but how would peer2 receive the stream arg if it wasn't in the same browser? In the github code 'stream' is never sent via socket.emit.
Update: This is based on the github link. So I remove the getUserMedia from the beginningand made the init() run on its own.
// add my stream to all peers in the room dynamically
function addMyStreamDynamic(stream) {
for (let index in peers) {
peers[index].addStream(stream);
}
}
function addMyVideoStream() {
navigator.mediaDevices.getUserMedia(constraints).then(stream => {
localVideo.srcObject = stream;
localStream = stream;
addMyStreamDynamic(stream);
}).catch(e => alert(`getUserMedia error ${e.name}`))
}
When calling addMyVideoStream it adds the stream to other peers but it's not complete. When running it before a user joins, the stream does not get sent.
Update2: The code above works but only when the initiator calls it.
It seems that dynamically adding a stream as a non-initiator is much more involved. I just created a dummy stream and later replace the track.