Giter Site home page Giter Site logo

telemantra-healthcare / use-twilio-video Goto Github PK

View Code? Open in Web Editor NEW

This project forked from nlatifahulfah/use-twilio-video

0.0 0.0 0.0 411 KB

React hooks to manage twilio video state in React application

Shell 1.37% JavaScript 96.19% CSS 0.32% HTML 2.12%

use-twilio-video's Introduction

use-twilio-video

React hooks to manage twilio video state in React application

NPM JavaScript Style Guide

Features

  • connect and disconnect room
  • toggle mute camera
  • toggle mute microphone
  • get dominant speaker

Install

npm install --save twilio-video use-twilio-video

Prerequisite

You need Twilio Access Token to use Twilio Video. You can use Testing Tools in the Twilio Console to generate the token. You can read the guide here.

Or you can also follow the next instruction while running the sample project in folder example. To run example:

  1. From root repo directory, change directory to example folder: cd example
  2. Install dependencies: npm install
  3. Copy .env.example and rename to .env
  4. Add your Twilio API Key to the .env file. You can get your API Key from your Twilio account. You can follow this guide.
  5. Run server to generate token: npm run server
  6. Open different tab and run the react app: npm start

Usage

There are two main hooks, useRoom and useTrack.

useRoom is used to manage room state. In Twilio, a Room represents a real-time audio, data, video, and/or screen-share session, and is the basic building block for a Programmable Video application.

useTrack is used to manage tracks in a room. In Twilio, Tracks represent the individual audio, data, and video media streams that are shared within a Room. This tracks are shared by Participants. Participants represent client applications that are connected to a Room and sharing audio, data, and/or video media with one another.

Room Participant and Track in Twilio

The following are the minimum components needed to be able to create a simple video call application using twilio and use-twilio-video.

  1. Create a component that represent a Room.

    // Room.js
    import Participant from './Participant'
    import { useRoom } from 'use-twilio-video'
    
    function Room ({ token, roomName }) {
      const { room, error, connectRoom, disconnectRoom, localParticipant, remoteParticipants, dominantSpeaker, isCameraOn, toggleCamera, isMicrophoneOn, toggleMicrophone } = useRoom()
    
      
      useEffect(() => {
        if (!room && token && roomName) {
          connectRoom({ token, options: { name: roomName, dominantSpeaker: true } })
          return () => disconnectRoom()
        }
      }, [connectRoom, disconnectRoom, room, roomName, token])
    
      // ... other
    
      // usage example in simple component
      if (room)
        return (
          <div>
            <div>
              <button onClick={() => disconnectRoom()}>disconnect</button>
              <button onClick={() => toggleCamera()}>
                {isCameraOn ? 'turn off camera' : 'turn on camera'}
              </button>
              <button onClick={() => toggleMicrophone()}>
                {isMicrophoneOn ? 'turn off mic' : 'turn on mic'}
              </button>
            </div>
    
            <div>Local participant: {JSON.stringify(localParticipant?.identity)}</div>
            <Participant participant={localParticipant} />
    
            <div>
              Remote participants:{' '}
              {JSON.stringify(remoteParticipants.map(v => v.identity))}
            </div>
    
            <div>Dominant speaker: {JSON.stringify(dominantSpeaker?.identity)}</div>
    
            <div>
              {remoteParticipants.map(p => (
                <Participant participant={p} />
              ))}
            </div>
          </div>
        )
    
      // ... other
    }
  2. Create a component represent Participants.

    // Participant.js
    import AudioTrack from './AudioTrack'
    import VideoTrack from './VideoTrack'
    import { useTrack } from 'use-twilio-video'
    
    function Participant ({ participant }) {
      const { videoOn, audioOn, videoTrack, audioTrack } = useTrack({ participant })
    
      return (
        <div>
          {videoOn ? <VideoTrack track={videoTrack} /> : 'video off'}
          <br />
          {audioOn ? <AudioTrack track={audioTrack} /> : 'audio off'}
        </div>
      )
    }
    
    export default Participant
  3. Create two components, to attach participants' video and audio

    // VideoTrack.js
    import { useEffect, useRef } from 'react'
    
    export default function VideoTrack ({ track }) {
      const ref = useRef()
    
      useEffect(() => {
        if (track) {
          const el = ref.current
          track.attach(el)
    
          return () => {
            track.detach(el)
          }
        }
      }, [track])
    
      return <video style={{ maxWidth: '100%' }} ref={ref} />
    }
    // AudioTrack.js
    import { useEffect, useRef } from 'react'
    
    export default function AudioTrack ({ track }) {
      const ref = useRef()
    
      useEffect(() => {
        if (track) {
          const el = ref.current
          track.attach(el)
    
          return () => {
            track.detach(el)
          }
        }
      }, [track])
    
      return <audio ref={ref} />
    }    

License

MIT © Nur Latifah Ulfah


This hook is created using create-react-hook.

use-twilio-video's People

Contributors

nlatifahulfah avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.