twiliotwilio-apitwilio-click-to-call

how to mute/unmute pause/unpause audio and video in twilio video call


init: function(config){
    var that = this;

    that.CONFIG = config;

    that.video = Twilio.Video;
    that.CONFIG.videoCall = true;
    that.CONFIG.audioCall =true;
    that.CONFIG.audioCallTrackCount =0;
    that.CONFIG.videoCallTrackCount =0;
    //alert message instance
    that.ALERT_MESSAGES = Object.create(AlertMessage).init();

    //ajaxing instance
    that.AJAXING = Object.create(Ajaxing);
    $(".fullscreen-btn").addClass('hide');
    window.videoCallObject = that;
    that.cachePageConstants();
    //that.getTwilioTokenFromRestAPI();

    return that;
},

cachePageConstants: function(){
   var that = this;
    $("#buttonCall").on("click", function(e){
       e.preventDefault();
       console.log("video button clicked");
        $("#buttonCall").hide();
        $("#audioCall").hide();
        $("#buttonCallEnd").show();
        $(".mute-btns").removeClass('hide');
        document.getElementById('connecting').innerHTML = '<span style="color:#69C4CB;"><img src="/resources/css/images/refresh_gif.gif" />Calling...</span>';
      that.CONFIG.videoCall =true;
      that.getTwilioTokenFromRestAPI();
    });
    $("#audioCall").on("click", function(e){
       e.preventDefault();
       console.log("Audio button clicked");
        $("#buttonCall").hide();
        $("#audioCall").hide();
        $("#buttonCallEnd").show();
        $(".mute-btns").removeClass('hide');
        document.getElementById('connecting').innerHTML = '<span style="color:#69C4CB;"><img src="/resources/css/images/refresh_gif.gif" />Calling...</span>';
      that.CONFIG.videoCall = false;
      that.CONFIG.audioCall =true;
      that.getTwilioTokenFromRestAPI();
    });

    $("#buttonRefresh").on("click", function(e){
        e.preventDefault();
        that.refreshPatientStatus(true);
    });

    $("#buttonCallEnd").on("click", function(e){
       e.preventDefault();
       console.log("Call end button clicked");
        $("#buttonCallEnd").hide();
        $("#buttonCall").show();
        $("#audioCall").show();
        $(".mute-btns").addClass('hide');
        that.leaveRoomIfJoined();
    });
    $('.fullscreen-btn').on('click', function(){
        $(this).parent().toggleClass('fullscreen');
    });
},
getTwilioTokenFromRestAPI: function(){
    var that = this,
    postRequestActions = {
        "successCallBack": that.onGettingToken,
        "loading": $("#connecting"),
        "ajaxType": "GET"
    };

    that.AJAXING.sendRequest(that.CONFIG.baseUrl+ "/services/v3/twilio/getTwilioToken?patientUuid="+UUID+"&providerUserId="+providerUserId+"&requestedFrom="+"COACH", null, postRequestActions);
},


onGettingToken: function(data){

    var that = window.videoCallObject;
    that.CONFIG.data=data;
    if(data){
          that.CONFIG.TOKEN = data.token;
          $("#connecting").removeClass("hide");
          $("#connecting").show();
          that.sendNotificationForcall(data);
          that.initTwilioCall(data.token,data.room);
    }else{
        that.ALERT_MESSAGES.showAlertMessage($("#terminatedMessage"), "Unable to get token from rest API", that.ALERT_MESSAGES.ERROR);
    }
},
//send Video call Notification to client.
sendNotificationForcall:function (data) {

  var that = this,
    requestActions = {
       "ajaxType": "GET"
    };
  var type = "CREATE_CALL"
  var callType;
  if(that.CONFIG.videoCall)
    callType = "VIDEO_CALL";
  else
    callType = "AUDIO_CALL";
  /*that.AJAXING.sendRequest(that.CONFIG.baseUrl+ "/services/v3/twilio/sendTwilioVideoNotification?patientId="+patId+"&providerUserId="+data.providerUserId+"&roomName="+data.roomName+"&callType="+callType+"&type="+type, null, requestActions);*/

},
 //send Video call Notification to client.
sendNotificationForCallCancel:function (data,type) {

  var that = this,
    requestActions = {
       "ajaxType": "GET"
    };
  var callType;
  if(that.CONFIG.videoCall)
    callType = "VIDEO_CALL";
  else
    callType = "AUDIO_CALL";

  /*that.AJAXING.sendRequest(that.CONFIG.baseUrl+ "/services/v3/twilio/sendTwilioVideoNotification?patientId="+patId+"&providerUserId="+data.providerUserId+"&roomName="+data.roomName+"&callType="+callType+"&type="+type, null, requestActions);*/

},
initTwilioCall: function (token,room) {
  var that = window.videoCallObject;
    that.video.connect(token, {audio: that.CONFIG.audioCall,
          name: room,
          video: that.CONFIG.videoCall
        }).then(function(room) {
         that.onParticipantConnected(room);

          //room.disconnect();
        }, function(error) {
            //console.error('Unable to connect to Room: ' +  error.message);
            that.ALERT_MESSAGES.showAlertMessage($("#terminatedMessage"), "Unable to get token from rest API", error.message);
    });


},
onParticipantConnected: function (room) {
   var that = window.videoCallObject;
    that.CONFIG.activeRoom=room;
    // Attach LocalParticipant's Tracks, if not already attached.
    that.CONFIG.previewContainer = document.getElementById('local-media');
    var previewContainer = that.CONFIG.previewContainer;

    if (!previewContainer.querySelector('video')) {
      document.getElementById('connecting').innerHTML = '<span style="color:Blue;"><img src="/resources/css/images/refresh_gif.gif" />Connecting...</span>';
        //that.attachParticipantTracks(room.localParticipant, previewContainer);

    }
  room.on('participantConnected', function(participant) {

        room.participants.forEach(function(participant) {
            //console.log("Already in Room: '" + participant.identity + "'");
            var previewContainer = document.getElementById('videoContainer');
            that.CONFIG.activeRoom.previewContainer=previewContainer;
            that.attachParticipantTracks(participant, previewContainer);
        });
            //console.log('A remote Participant connected: ', participant);
            $(".fullscreen-btn").removeClass('hide');
            document.getElementById('connecting').innerHTML = '<span style="color:green;">Call active</span>';

    });

    // When a Participant adds a Track, attach it to the DOM.
    room.on('trackAdded', function(track, participant) {
      if(track.kind =='video' && that.CONFIG.videoCall == false){
          that.CONFIG.videoCall = true;
          that.video.createLocalVideoTrack().then(function(localTrack) {

          room.localParticipant.addTrack(localTrack);
            that.attachParticipantTracks(room.localParticipant, that.CONFIG.previewContainer);
          });
        }else{
                room.localParticipant.tracks.forEach(track => {
                if(track.kind == 'video'){
                  track.enable();

                }
            });
            if(track.kind =='video')
                that.attachParticipantTracks(room.localParticipant, that.CONFIG.previewContainer);   

        }
       var previewContainer = document.getElementById('videoContainer');
       that.attachTracks([track], previewContainer);
    });
     // When a Participant removes a Track, detach it from the DOM.
    room.on('trackRemoved', function(track, participant) {
        if(track.kind =='video'){
          that.detachSingleTracks(room.localParticipant);
        }

        that.detachTracks([track]);
     });

    // When a Participant leaves the Room, detach its Tracks.
    room.on('participantDisconnected', function(participant) {
        $("#buttonCall").show();
        $("#audioCall").show();
        $("#buttonCallEnd").hide();
        $(".mute-btns").addClass('hide');
        that.detachParticipantTracks(participant);
         that.detachParticipantTracks(room.localParticipant);
         that.leaveRoomIfJoined();

    });

    // Once the LocalParticipant leaves the room, detach the Tracks
    // of all Participants, including that of the LocalParticipant.
    room.on('disconnected', function() {
        $("#buttonCall").show();
        $("#audioCall").show();
        $("#buttonCallEnd").hide();
        $(".mute-btns").addClass('hide');
        that.detachParticipantTracks(room.localParticipant);

        room.participants.forEach(that.detachParticipantTracks);

    });



},
// Attach the Participant's Tracks to the DOM.
attachParticipantTracks:function (participant, container) {
    var that = window.videoCallObject;
    var tracks = Array.from(participant.tracks.values());
    that.attachTracks(tracks, container);


},
// Attach the Tracks to the DOM.
attachTracks:function(tracks, container) {
  var that = window.videoCallObject;
  tracks.forEach(function(track) {
      if(track.kind == 'audio' && that.CONFIG.audioCallTrackCount == 0){
        container.appendChild(track.attach());
        that.CONFIG.audioCallTrackCount = 1;
      }else if(track.kind == 'video' && that.CONFIG.videoCallTrackCount == 0){
         //console.log("video");
        container.appendChild(track.attach());
        that.CONFIG.videoCallTrackCount = 1;
      }
      else{
        container.appendChild(track.attach());
      }
  });
},
// Detach the Tracks from the DOM.
detachTracks:function(tracks) {
 tracks.forEach(function(track) {

    track.detach().forEach(function(detachedElement) {
      detachedElement.remove();
    });

  });

  $("#connecting").addClass("hide");
  $(".fullscreen-btn").addClass('hide');

},
// Detach the Participant's Tracks from the DOM.
detachParticipantTracks:function(participant) {

    var that = window.videoCallObject;
    var tracks;
    if(participant.tracks !='undefined'){
      tracks = Array.from(participant.tracks.values());
    }
    that.detachTracks(tracks);
},

detachSingleTracks:function(participant) {

    var that = window.videoCallObject;
    var tracks;

    participant.tracks.forEach(track => {

      if(track.kind == 'video'){

        track.detach().forEach(function(detachedElement) {
          detachedElement.remove();
        });
        track.disable();
      }
  });

},


leaveRoomIfJoined:function() {
 var that = window.videoCallObject;
  if (that.CONFIG.activeRoom) {
      that.CONFIG.activeRoom.disconnect();

  that.sendNotificationForCallCancel(that.CONFIG.data,'CANCEL_CALL');
    //that.detachParticipantTracks(that.CONFIG.activeRoom.participant);
  }
}

}

JavaScript beginner here!

I am trying to mute/unmute and pause/unpause audio and video but I have no clue how to do it.

I want the button to mute/unmute the audio when clicked and pause/unpause video from my local when i click another button.This is the full javascript code.

Now please edit this and solve the prolblem.


Solution

  • Twilio developer evangelist here.

    You've not included the bits of your code that actually setup the call, so I can only point you in the right direction.

    When you join a room, your local media is accessible from the localParticipant object in the room. A localParticpant is an instance of Participant, so you can call on their audioTracks or videoTracks, which both implement LocalTrack, when you want to.

    If you want to mute audio, for example, you can call

    room.localParticipant.audioTracks.forEach(function(trackId, track) {
      track.disable();
    });
    

    You can do the same for videoTracks. To enable tracks again, you'd do the same but with track.enable().

    Let me know if that helps at all.