Search code examples
javascriptphpopentoktokbox

Tokbox video chat query


I Am developing website using Tokbox video chatting , i have to run a timer if both users are connected and if they videos are visibled.

I Am using below code and if anyone users connected it calls the start_countdown function.

 session.on('streamCreated', function(event) {
    event.streams.forEach(function(stream) {
      if(stream.connection.connectionId != session.connection.connectionId) {
        // subscribe(stream);
        console.log("New stream in the session: " + event);
        // console.log(event);
        // console.log(stream);
        // start_countdown();
      }
    });
  });

but i need to call the countdown function if both users grant access to their video. Can anyone help on this.


Solution

  • The first idea to understand is that since you are doing this in the client code, each participant would have their own value for the countdown because both browsers are independently running the timer. This is probably fine if you are just trying to display the time that both users have been connected (or have remaining) in the UI. But if instead you are trying to maintain one true clock, this approach is probably not best.

    Next, in OpenTok, a streamCreated event is triggered from the Session when a remote stream becomes available. The Publisher also triggers a streamCreated event when the local stream has started being sent (after the local user grants access). If you know that there will be only 2 users in the session, you can find out when both users have joined by listening for both of these events. The following is an example:

    // Initialize flags
    var publishing = false;
    var subscribing = false;
    
    // TODO: create a publisher (either using session.publish() or OT.initPublisher()) and publish a stream after the session has connected
    
    // Listen to the events
    session.on('streamCreated', function(event) {
      // event.stream will always be a remote stream so the connection comparison is unnecessary
      // TODO: subscribe to the stream
      subscribing = true;
      // Check if both criteria have been met
      checkStartCountdown();
    });
    
    publisher.on('streamCreated', function(event) {
      publishing = true;
      // Check if both criteria have been met
      checkStartCountdown();
    });
    
    function checkStartCountdown() {
      if (publishing && subscribing) {
        // TODO: start_countdown is the function as you described in your question
        start_countdown();
      }
    }