项目作者: agnostech

项目描述 :
React Hooks for Agora NG SDK https://agoraio-community.github.io/AgoraWebSDK-NG/en/
高级语言: JavaScript
项目地址: git://github.com/agnostech/react-agora-ng.git
创建时间: 2020-08-01T18:04:33Z
项目社区:https://github.com/agnostech/react-agora-ng

开源协议:MIT License

下载


react-agora-ng

GitHub issues GitHub forks GitHub stars GitHub license Twitter

Simple and generic React hooks for Agora NG SDK - https://agoraio-community.github.io/AgoraWebSDK-NG/en/

Installation

npm install --save @agnostech/react-agora-ng agora-rtc-sdk-ng

or

yarn add @agnostech/react-agora-ng agora-rtc-sdk-ng

TL;DR

  1. Create the AgoraRTC client and pass it to the AgoraProvider
  2. Register for agora events by calling useCallEvents()
  3. Call useJoinCall() to start a call
  4. Call useCallControls() to start/stop audio/video, leave the call or share your screen.

Usage

1. Initialize AgoraRTC client and pass it to AgoraProvider along with appId which is available in your Agora dashboard

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import App from './App';
  4. import {AgoraProvider} from '@agnostech/react-agora-ng';
  5. import AgoraRTC from "agora-rtc-sdk-ng"
  6. // mode can be rtc or live. Refer Agora NG SDK docs for more info
  7. const client = AgoraRTC.createClient({mode: "rtc", codec: "vp8"});
  8. const Test = () => (
  9. <AgoraProvider client={client} appId={'<YOUR_APP_ID>'}>
  10. <App></App>
  11. </AgoraProvider>
  12. );
  13. ReactDOM.render(
  14. <Test></Test>,
  15. document.getElementById('root')
  16. );

2. Register for Agora Events

It is important and recommended to register for events before interacting with Agora to avoid missing any events. This library will emit all the events mentioned here.

  1. import React, {useEffect, useState} from 'react';
  2. import {useCallEvents} from '@agnostech/react-agora-ng';
  3. const App = () => {
  4. //register event listeners
  5. const {events} = useCallEvents();
  6. //array of users in this call
  7. const [users, setUsers] = useState([]);
  8. useEffect(() => {
  9. switch (events.event) {
  10. case "user-joined":
  11. /* add the newly joined user to the array of users.
  12. here the event object is
  13. {
  14. event: 'user-joined',
  15. data: {
  16. remoteUser: {...newly connected user object}
  17. }
  18. }
  19. */
  20. setUsers(users => [...users, events.data.remoteUser]);
  21. break;
  22. case "user-published":
  23. console.log("user published");
  24. break;
  25. case "user-unpublished":
  26. console.log("user unpublished");
  27. break;
  28. case "user-left":
  29. //remove the user from the array on leaving the call.
  30. console.log('user left');
  31. setUsers(users => {
  32. const user = events.data.remoteUser;
  33. return users.filter(oldUser => oldUser.uid !== user.uid);
  34. });
  35. break;
  36. // check Agora docs for all the supported events.
  37. }
  38. }, [events, setUsers])
  39. }
  40. return (
  41. <div className="App">
  42. <div style={{height: '40%'}}>
  43. {users.map(user => (
  44. <div key={user.uid.toString()} style={{height: '300px', width: '300px'}} id={user.uid.toString()}>
  45. {user.videoTrack && user.videoTrack.play(user.uid.toString())}
  46. {user.audioTrack && user.audioTrack.play()}
  47. </div>
  48. ))}
  49. </div>
  50. </div>
  51. );
  52. export default App;

useCallEvents()

Returns

  • events - An object having event information
    • event - The event that was fired from Agora. (For eg. user-joined, user-left, etc.)
    • data - This consist of event specific data object . For eg. If the user-joined event is received, data will contain a remoteUser key which will have the user object connected to the call.

These events should be used to control the UI for showing all the users in the call, volume levels, control video feed for each user, etc. Check the example mentioned above.


3. Join the channel to start the call

  1. import React, {useEffect, useState} from 'react';
  2. import {useCallEvents, useJoinCall} from '@agnostech/react-agora-ng';
  3. const App = () => {
  4. //register event listeners
  5. const {events} = useCallEvents();
  6. //array of users in this call
  7. const [users, setUsers] = useState([]);
  8. // join the call
  9. const {loading, error, localUserId} = useJoinCall({
  10. channel: 'lmpvc',
  11. userId: null,
  12. token: null,
  13. localVideoDiv: 'test'
  14. });
  15. useEffect(() => {
  16. switch (events.event) {
  17. case "user-joined":
  18. console.log("user joined");
  19. setUsers(users => [...users, events.data.remoteUser]);
  20. break;
  21. case "user-published":
  22. console.log("user published");
  23. break;
  24. case "user-unpublished":
  25. console.log("user unpublished");
  26. break;
  27. case "user-left":
  28. console.log('user left');
  29. setUsers(users => {
  30. const user = events.data.remoteUser;
  31. return users.filter(oldUser => oldUser.uid !== user.uid);
  32. });
  33. break;
  34. // check Agora docs for all the supported evebts.
  35. }
  36. }, [events, setUsers])
  37. }
  38. return (
  39. <div className="App">
  40. // this div will be used by Agora to appent the local user video
  41. <div style={{height: '60%'}} id={'test'}></div>
  42. <div style={{height: '40%'}}>
  43. {users.map(user => (
  44. <div key={user.uid.toString()} style={{height: '300px', width: '300px'}} id={user.uid.toString()}>
  45. {user.videoTrack && user.videoTrack.play(user.uid.toString())}
  46. {user.audioTrack && user.audioTrack.play()}
  47. </div>
  48. ))}
  49. </div>
  50. </div>
  51. );
  52. export default App;

Calling useJoinCall() will

  • connect the local user to the mentioned channel
  • ask the user for video and audio permissions
  • publish audio and video tracks on the channel
  • On successful connection, it returns the uid of the connected local user as localUserId, sets loading as false or returns an error if there was an issue in the process.

    useJoinCall({channel, token, userId, localVideoDiv})

    Parameters:

  • channel (required) - channel name of the call

  • token - required if authentication is enabled.
  • userId - A unique id for the current user. If sent as null, Agora will generate a unique uid for this user.
  • localVideoDiv (required) - The id string of the local div to show the local user’s video feed in the UI.

Returns

  • loading - This represents the connection status. It is true by default. Once the connection is established, it becomes false. You can use this parameter to show a different UI before the connection is established.
  • localUserId - The uid of the local user connected on the call.
  • error - If there is any error during the call joining process, it can be checked here.

4. You can call useCallControls to toggle audio/video, leaving a meeting or start sharing your screen

  1. import React, {useEffect} from 'react';
  2. import {useCallEvents, useJoinCall, useCallControls} from '@agnostech/react-agora-ng';
  3. const App = () => {
  4. //register event listeners
  5. const {events} = useCallEvents();
  6. // join the call
  7. const {loading, error, localUserId} = useJoinCall({
  8. channel: 'lmpvc',
  9. userId: null,
  10. token: null,
  11. localVideoDiv: 'test'
  12. });
  13. //get the call controlls
  14. const { toggleVideo,
  15. toggleAudio,
  16. leave,
  17. startScreenShare,
  18. stopScreenShare
  19. } = useCallControls();
  20. useEffect(() => {
  21. switch (events.event) {
  22. case "user-joined":
  23. console.log("user joined");
  24. break;
  25. case "user-published":
  26. console.log("user published");
  27. break;
  28. case "user-unpublished":
  29. console.log("user unpublished");
  30. break;
  31. case "user-left":
  32. console.log('user left');
  33. break;
  34. // check Agora docs for all the supported evebts.
  35. }
  36. }, [events])
  37. }
  38. return (
  39. <div className="App">
  40. //call method inside any event handler
  41. <button onClick={() => toggleVideo('test')}>toggle video</button>
  42. <button onClick={() => toggleAudio()}>toggle audio</button>
  43. <button onClick={() => leave()}>leave meeting</button>
  44. <button onClick={() => startScreenShare({
  45. channel: 'lmpvc',
  46. token: null,
  47. })}>start screen share</button>
  48. <button onClick={() => stopScreenShare()}>stop screen share</button>
  49. <div style={{height: '60%'}} id={'test'}></div>
  50. <div style={{height: '40%'}}>
  51. {users.map(user => (
  52. <div key={user.uid.toString()} style={{height: '300px', width: '300px'}} id={user.uid.toString()}>
  53. {user.videoTrack && user.videoTrack.play(user.uid.toString())}
  54. {user.audioTrack && user.audioTrack.play()}
  55. </div>
  56. ))}
  57. </div>
  58. </div>
  59. );
  60. export default App;

useCallControls()

Returns

  • toggleVideo(localVideoDivId) - To start/stop your video stream. You need to pass the id of the div to play the local user’s video stream.
  • toggleAudio() - To start/stop your microphone audio stream.
  • leave() - To leave the call.
  • startScreenShare({channel, token}) - To start screen sharing.
    • channel (required) - channel name of the call
    • token - required if authentication is enabled.
  • stopScreeShare() - To stop screen sharing.

(Optional) You can access the AgoraRTC client using the useAgoraClient() hook.

TODO

  • Add example project
  • Write tests
  • CI/CD
  • Efficient error handling
  • Don’t publish stream in live mode if the user role is not host
  • Implement RTM for sending messages during the calls
  • Implement call invitations
  • Add option to send a message to peers