# Twilio JavaScript SDK to VidyoClient JavaScript SDK

This guide walks you through how to migrate your existing [Twilio Video implementation](https://www.npmjs.com/package/twilio-video) to [Vidyo Javascript SDK](https://www.npmjs.com/package/vidyoclient-nativewebrtc-sdk). To complement this guide, we have also developed a sample app that can switch between the Twilio SDK and Vidyo SDK by simply using a build-time configuration. This app provides a handy “translation guide” between Twilio and VidyoClient (Connector) JavaScript SDK. Navigate here for complete source code reference:

{% embed url="<https://github.com/VidyoAPI-SDK/twilio-to-vidyo-migration-sample>" %}
Twilio to Vidyo Migration Sample
{% endembed %}

If you are starting a new project from scratch, we recommend looking at:

{% embed url="<https://github.com/VidyoAPI-SDK/nativeWebRTC-getting-started-sample>" %}
Getting Started with VidyoClient (Connector) SDK for JS
{% endembed %}

{% embed url="<https://github.com/VidyoAPI-SDK/nativeWebRTC-vidyoconnect-sample>" %}
Full Featured Sample Application
{% endembed %}

## Install

To begin, install the VidyoClient JavaScript SDK:

```bash
npm install vidyoclient-nativewebrtc-sdk
```

You can uninstall the Twilio SDK from your project by uninstalling the package:

```bash
npm uninstall twilio-video 
```

## Authorize

Twilio uses JSON Web Tokens (JWT) to generate a token for users to join sessions. Vidyo follows a different model: a meeting room is created on backend middleware (referred to as the <mark style="color:blue;">VidyoPortal</mark>) which generates a meeting link, and users join the room through their browser by clicking on the meeting link. For more information visit [Getting Started](/vidyoplatform/getting-started.md).

## Join meeting room

{% tabs %}
{% tab title="Twilio" %}
Twilio requires a token to join a meeting room.

```javascript
import * as TwilioVideo from 'twilio-video' 
 
var twilioVideo = TwilioVideo 
var twilioRoom 
 
twilioVideo.connect(TOKEN, {name: 'yourName', audio: false, video: false, dominantSpeaker: true}). then((room) => { 
    twilioRoom = room 
}) 
```

{% endtab %}

{% tab title="Vidyo" %}
Joining a meeting in the Vidyo SDK requires the following:

1. URL of the VidyoPortal that owns/created the room;
2. Room key;
3. Room pass code (optional). If this is set for a specific room, users must enter the pass code to enter the room. This pass code is typically received as part of the meeting invitation and is available at the moment when the room is created on VidyoPortal.

The Vidyo SDK automatically sets the audio, video, and dominant speaker parameters, so the user does not need to set these parameters explicitly.

```javascript
import { VC } from "vidyoclient-nativewebrtc-sdk"; 
 
// create vidyoConnector object 
vidyoConnector = await VC.CreateVidyoConnector({ 
        viewId: "renderer", // Div ID where video will be rendered 
        viewStyle: "VIDYO_CONNECTORVIEWSTYLE_Default",         remoteParticipants: 8,  // max number of video tiles to render to render 
        logFileFilter: "debug@VidyoClient", 
        logFileName: "", 
        userData: 0, 
        constraints: {} 
    }); 
 
// connect to room 
await vidyoConnector.ConnectToRoomAsGuest({ 
        host: portalURL,  // URl of the portal 
        roomKey: roomKey, // room ID 
        displayName: ‘yourName’, // users display name 
        roomPin: roomPin, // optional pin 
        onSuccess: () => { 
                console.log(`vidyoConnector.ConnectToRoomAsGuest : onSuccess callback received`); 
            }, 
            onFailure: (reason) => { 
                console.error("vidyoConnector.Connect : onFailure callback received", reason); 
            }, 
            onDisconnected: (reason) => { 
                console.log("vidyoConnector.Connect : onDisconnected callback received", reason); 
            } 
   });
```

{% endtab %}
{% endtabs %}

## Video

While Twilio requires [additional configuration](https://www.twilio.com/docs/video/tutorials/developing-high-quality-video-applications) to set the quality of the video, Vidyo handles the video quality automatically based on network conditions and device capabilities. In low bandwidth conditions Vidyo prioritizes audio over video, and shared content video tiles over participant video. Vidyo also supports configuration options to limit maximum resolution of local or remote video.&#x20;

### Render local video

{% tabs %}
{% tab title="Twilio" %}
Twilio has a concept of video and audio tracks. To render the self-view, Twilio appends a video element inside the specified div.

```javascript
const wrapVideo = (video, id, dataId) => { 
    const div = document.createElement('div'); 
    div.append(video); 
    if(id) { 
        div.id = id; 
    } 
    if(dataId) { 
        div.setAttribute('data-id', dataId); 
   } 
    return div; 
} 
```

```javascript
const videoTrack = await twilioVideo.createLocalVideoTrack(); 
    const trackElement = wrapVideo(videoTrack.attach()); 
    window.currentLocalCamera = { 
        track: videoTrack, 
        trackElement 
  }; 
    document.getElementById('renderer').appendChild(trackElement); 
```

{% endtab %}

{% tab title="Vidyo" %}
Vidyo has a <mark style="color:blue;">SelectLocalCamera</mark> function to select which of the connected cameras to use in the call:

```javascript
vidyoConnector.SelectLocalCamera({localCamera: selectedCamera}); 
```

{% hint style="info" %}
Vidyo also selects local camera automatically based on system default camera device. So you don't have to call above API explicitly if you are fine with default device selection.
{% endhint %}
{% endtab %}
{% endtabs %}

### Turn the camera off

{% tabs %}
{% tab title="Twilio" %}
Since Twilio video is track based - you must loop through each video track to unpublish the video, stop the video camera, and remove the video element from the DOM:

```javascript
twilioRoom?.localParticipant.videoTracks.forEach(track => { 
            track.unpublish(); 
            track.track.disable(); 
    }); 
```

{% endtab %}

{% tab title="Vidyo" %}
Vidyo’s implementation requires you to call a single API function to disable the local camera:

```javascript
vidyoConnector.SetCameraPrivacy({privacy: true}); 
```

{% endtab %}
{% endtabs %}

### Render remote user video

{% tabs %}
{% tab title="Twilio" %}
Twilio uses <mark style="color:blue;">participantConnected</mark> and <mark style="color:blue;">trackSubscribed</mark> event listeners to determine which remote videos to render:

```javascript
twilioRoom.on('participantConnected', (participant) => { 
 
    participant.on('trackSubscribed', (track) => { 
        // a user turned on their video, render it 
        document.getElementById('twilio-user-view-div').appendChild(track.attach()); 
    }); 
    participant.on('trackUnsubscribed', (track) => { 
        // a user turned off their video, stop rendering it 
        var selfTwilioVideo = document.getElementById('twilio-user-view-div') 
        selfTwilioVideo.querySelector('video').remove() 
    }) 
}) 
```

{% endtab %}

{% tab title="Vidyo" %}
Vidyo manages the video rendering part automatically, but the user can also register callbacks to, for example, listen to when a participant joins or leaves a room:

```javascript
vidyoConnector.RegisterParticipantEventListener({ 
        onJoined: function(participant) { 
                // user joined 
        }, 
        onLeft: function(participant) { 
                // user left 
        }, 
}) 
```

{% endtab %}
{% endtabs %}

## Audio

### Select local microphone

{% tabs %}
{% tab title="Twilio" %}
Since Twilio audio is track based - you must loop through each audio track to start the audio, and add the audio element to the DOM:

```javascript
twilioVideo.createLocalAudioTrack().then((localAudioTrack) => { 
    twilioRoom.localParticipant.publishTrack(localAudioTrack); 
    const audioElement = localAudioTrack.attach(); 
    document.body.appendChild(audioElement); 
}) 
```

{% endtab %}

{% tab title="Vidyo" %}
Vidyo has a <mark style="color:blue;">SelectLocalMicrophone</mark> function to select which of the connected microphones to use in the call:

```javascript
vidyoConnector.SelectLocalMicrophone({localMicrophone: selectedMicrophone]}); 
```

{% hint style="info" %}
Same as with video - you don't have to explicitly call this API if you are good with default automatic selection by Vidyo SDK.
{% endhint %}
{% endtab %}
{% endtabs %}

### Mute/unmute microphone

{% tabs %}
{% tab title="Twilio" %}
Since Twilio API is track based - you must loop through each audio track to mute/unmute the microphone.

Mute:

```javascript
twilioRoom.localParticipant.audioTracks.forEach((publication) => { 
    publication.track.disable() 
}) 
```

Unmute:

```javascript
twilioRoom.localParticipant.audioTracks.forEach((publication) => { 
    publication.track.enable() 
}) 
```

{% endtab %}

{% tab title="Vidyo" %}
Use the <mark style="color:blue;">SetMicrophonePrivacy</mark> function to set the microphone state.

Mute:

```javascript
vidyoConnector.SetMicrophonePrivacy({privacy: true}); 
```

Unmute:

```javascript
vidyoConnector.SetMicrophonePrivacy({privacy: false}); 
```

{% endtab %}
{% endtabs %}

## Event listeners

{% tabs %}
{% tab title="Twilio" %}
Twilio has event listeners for participant management, allowing you to detect changes that occur during a meeting.

User joins or leaves a session:

```javascript
twilioRoom.on('participantConnected', (participant) => { 
    // user joined 
}) 
 
twilioVideo.on('participantDisconnected', (participant) => { 
    // user left 
}) 
```

Active speaker changes:

```javascript
twilioVideo.on('dominantSpeakerChanged', (participant) => { 
    // new active speaker 
}) 
```

{% endtab %}

{% tab title="Vidyo" %}

Vidyo supports the concept of event listeners. Commonly used event listeners include:&#x20;

* <mark style="color:blue;">RegisterParticipantEventListener</mark> - listens for participant join/leave events&#x20;
* <mark style="color:blue;">RegisterRemoteCameraEventListener</mark> - listens for camera mute/unmute events&#x20;
* <mark style="color:blue;">RegisterRemoteMicrophoneEventListener</mark> - listens for microphone mute/unmute events&#x20;

For example:

```javascript
vidyoConnector.RegisterRemoteCameraEventListener({ 
        onAdded: function (remoteCamera, participant) { 
            // New remote camera is available 
        } 
        onRemoved: function (remoteCamera, participant) { 
            // Remote camera became unavailable 
      }, 
}) 
 
```

{% endtab %}
{% endtabs %}

## End session

{% tabs %}
{% tab title="Twilio" %}

```javascript
twilioVideo.disconnect() 
```

{% endtab %}

{% tab title="Vidyo" %}

```javascript
 vidyoConnector.Disconnect() 
```

{% endtab %}
{% endtabs %}

## Additional information

This guide covers only the fundamentals for migrating an application from the Twilio JavaScript SDK to the Vidyo JavaScript SDK. If you do not see a piece of functionality described in this guide, please take a look at our [API reference  ](https://static.vidyo.io/latest/docs/VidyoClientReferenceGuide.html)or the [VidyoPlatform Github page](https://github.com/VidyoAPI-SDK). \
If you have any technical questions or run into issues with your migration, you can reach out to the Support team at <support@vidyocloud.com> <br>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://enghouse-vidyo.gitbook.io/vidyoplatform/twilio-to-vidyo-migration/twilio-javascript-sdk-to-vidyoclient-javascript-sdk.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
