Essential SDK to Use Antmedia with React Native

Essential SDK to Use Antmedia with React Native

React Native AntMedia Port of webrtc-adaptor (AntMedia) to react-native using react-native-webrtc

React Native AntMedia

Essential SDK to use antmedia with React native.

Table of content

  1. What is RN AntMedia?
  2. Getting Started
  3. Using
  4. Hook Parameters
  5. Hook returned adaptor
  6. Help this project

1. What is RN AntMedia?

RN AntMedia is an port of web sdk of antmedia webrtc_adaptor to react-native using react-native-webrtc. Some functionalities is equal but others is an approach but have some differences.

Some functionalities is under development.

2. Getting Started

To use in your react-native projects, should be in pure react-native. And you need to install react-native-webrtc too. npm

    npm i rn-antmedia react-native-webrtc

yarn

    yarn add rn-antmedia react-native-webrtc

3. Using

import React, { useState, useRef, useCallback } from 'react';
import {SafeAreaView, Button} from 'react-native';
import {RTCView} from 'react-native-webrtc';
/* importing lib */
import { useAntMedia } from 'rn-antmedia';

const App = () => {
    const [localStream, setLocalStream] = useState('');
    const [remoteStream, setRemoteStream] = useState(null);
    const stream = useRef({id: ''}).current;

    const adaptor = useAntMedia({
    url: 'wss://testserver.com/WebRTCAppEE/websocket',
    mediaConstraints: {
      video: true,
      audio: true,
    },
    sdp_constraints: {
      offerToReceiveAudio: true,
      offerToReceiveVideo: true,
    },
        bandwidth: 300,
    callback(command, data) {
      switch (command) {
        case 'pong':
          break;
        case 'joinedTheRoom':
          if ('onJoinedRoom' in events) {
            const tok = data.ATTR_ROOM_NAME;
            this.initPeerConnection(data.streamId);
            this.publish(data.streamId, tok);

            const streams = data.streams;

            if (streams != null) {
              streams.forEach((item) => {
                if (item === stream.id) return;
                this.play(item, tok, roomId);
              });
            }
          }
          break;
        case 'streamJoined':
          if ('onStreamJoined' in events) {
            this.play(data.streamId, token, roomId);
          }
          break;
        default:
          break;
      }
    },
    callbackError: (err, data) => {
      console.error('callbackError', err, data);
    },
    });

    const handleConnect = useCallback(() => {
        if (adaptor) {
            const streamId = `12ans1`;
            const roomId = '5abcd1';

            stream.id = streamId;

            adaptor.joinRoom(roomId, streamId);
        };
    }, [adaptor]);

    useEffect(() => {
    if (adaptor) {
      const verify = () => {
        if (
          adaptor.localStream.current &&
          adaptor.localStream.current.toURL()
        ) {
          return setLocalStream(adaptor.localStream.current.toURL());
        }
        setTimeout(verify, 3000);
      };
      verify();
    }
    }, [adaptor]);

    useEffect(() => {
    if (adaptor && Object.keys(adaptor.remoteStreams).length > 0) {
      for (let i in adaptor.remoteStreams) {
        if (i !== stream.id) {
          let st =
            adaptor.remoteStreams[i][0] &&
            'toURL' in adaptor.remoteStreams[i][0]
              ? adaptor.remoteStreams[i][0].toURL()
              : null;
          setRemoteStream(st);
          break;
        } else {
          setRemoteStream(null);
        }
      }
    }
  }, [adaptor, stream.id]);

    return (
        <SafeAreaView style={{flex: 1;}}>
        {
            localStream && remoteStream ? (
                <>
                    <RTCView
                        style={{flex: 1}}
                        objectFit="cover"
                        streamURL={remoteStream}
                    />
                    <RTCView
                        style={{ width: 200, height: 200,  position: 'absolute', bottom: 0, right: 0, }}
                        objectFit="cover"
                        streamURL={localStream}
                    />
                </>
            ) : (
                <Button
                    onPress={handleConnect}
                    title="Join room"
                    color="#841584"
                    accessibilityLabel="Connect to antmedia"
                />
            )
        }
        </SafeAreaView>
    )
};

4. Hook Parameters

When you call hook function, you need to pass some of this params to work, by default the hook will start getUserMedia with mediaConstraints.

Params with ***** is mandatory acctually

  • *url: string with url to your antmedia server example "wss://testserver.com/WebRTCAppEE/websocket"
  • *mediaConstraints: object with constraints to getUserMedia (react-native-webrtc)
  • *sdp_constraints: object with constraints to RTCSessionDescription (react-native-webrtc)
  • peerconnection_config: object with peerconnection configurartion (react-native-webrtc)
  • *bandwidth: object with bandwidth config number or string example 300 or "unlimited"
  • callback: callback function when some event is fired by antmedia server by websocket
    • callback(this, message, data)
    • callback-this: is object returned by hook to use internally in callback
    • callback-message: is message returned by antmedia server
    • callback-data: is data returned by antmedia server (by the event could be undefined)
  • *callbackError: callback function when some error event is fired by antmedia server by websocket
    • callbackError(errorMessage, data)
    • callbackError-errorMessage: error message from antmedia event
    • callbackError-data: error data
  • *onopen: callback function called when connection is done between antmedia server and client
    • onopen-data: is data returned by onopen event in websocket connection

5. Hook returned adaptor

Params with ***** is mandatory

  • publish(*streamId, token): based on publish by antmedia webrtcAdaptor
  • joinRoom(*room, streamId): based on publish by antmedia webrtcAdaptor
  • leaveFromRoom(room: string): based on publish by antmedia webrtcAdaptor
  • join(*streamId): based on publish by antmedia webrtcAdaptor
  • leave(*streamId): based on publish by antmedia webrtcAdaptor
  • play(*streamId, token, room): based on publish by antmedia webrtcAdaptor
  • stop(*streamId): based on publish by antmedia webrtcAdaptor
  • localStream: this is local stream when the hook is started
  • remoteStreams: this is object with remote streams when have connection between peers, acctually localStream come inside remoteStream, be careful when use this to renderize the other peers
  • getUserMedia(*mediaConstrants): based on getUserMedia (react-native-webrtc)
  • getStreamInfo(*streamId): based on publish by antmedia webrtcAdaptor
  • signallingState(*streamId): this function return the signalling state of the gived stream id
  • initPeerConnection(*streamId): funcion to initPeerConnection between the stream id and the user
  • handleTurnVolume(): function to turn on/off the volume (by default is turned on)
  • handleTurnCamera(): function to turn on/off the camera (by default is turned on)
  • isTurnedOf: boolean to return the state of camera (true is turned on)
  • isMuted: boolean to return the state of volume (true is turned on)

6. Help this project

How could you help this project: open an issue when you find some error, open an pull request when you find the solution.

If this project help you, please consider to help me to develop this project continuously.

Download Details:

Author: TecladistaProd

Source Code: https://github.com/TecladistaProd/rn-antmedia

react-native react mobile-apps

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How native is React Native? | React Native vs Native App Development

Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.

React Native Mobile App Development

Skenix is providing React Native Development Services with qualified React Native App Developers. Get the best React Native App Development Services.

How React Native Is Shaping Mobile App Development

Are you a mobile app developer looking for more efficient tools for your projects? Mobile app development is getting tougher and tougher as the market continues to grow. As a developer, you need to develop Apps which meet the demands of your users. To achieve this, adopt the right tools, like the React Native development framework.

Top React Native Mobile App Development Companies in USA

Looking for top React Native mobile app development company in USA for Startups & Enterprise? Find out the top list of React Native mobile app development company in USA.

Which is the best React Native app development company in New York?

Hire top react native app development company in New York to build and develop custom react native mobile apps for Android & iOS with the latest features.