yjs / y-webrtc

WebRTC Connector for Yjs
MIT License
458 stars 111 forks source link

Handle 'stream' event #6

Closed callum-atwal closed 4 years ago

callum-atwal commented 4 years ago
callum-atwal commented 4 years ago

Would need to do something with that video tag though, it works if you just want any video tag off the page. It was okay for my use case

dmonad commented 4 years ago

Hey @callum-atwal ,

I agree with you, this would be a neat use-case and it would be nice if y-webrtc could provide a proper API to enable you to build this.

Conceptually, I don't like the idea to assume that there is a single video tag that all clients connect to. Even if we would allow the developer to specify a specific video-element for every user, I feel that we would make too many assumptions on how to build a conferencing solution.

Have you tried listening to the peers event? provider.on('peers', event => {}) is emitted every time a client is added or removed. Note that there are webrtc-peers and peers that communicate via broadcastchannel (communication within the browser)

Here is some sample code that you could use to listen to a stream object when a client is added:

provider.on('peers', event => {
  event.added.forEach(peerId => {
    const peer = event.webrtcPeers[peerId]
    // if peer is undefined it is a broadcastchannel connection
    if (peer) {
      this.peer.on('stream', stream => {
        const video = document.querySelector('video');
        if ('srcObject' in video) {
          video.srcObject = stream
        } else {
          video.src = window.URL.createObjectURL(stream) // for older browsers
        }
        video.play()
      })
      // here you can also stream your own video to the remote peer:
      peer.addStream(..)
    }
  })
})