Package Exports
- @100mslive/react-native-hms
- @100mslive/react-native-hms/lib/commonjs/index.js
- @100mslive/react-native-hms/lib/module/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@100mslive/react-native-hms) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
react-native-hms
React native wrapper for 100ms SDK
🏃 Run Example App
To run the Example app on your system, follow these steps -
- In the project root, run
npm install - Go to the example folder,
cd example - In the example folder, run
npm install - To run on Android, run
npx react-native run-android - To run on iOS, first install the pods in iOS folder,
cd ios; pod install. Then, set the development team in Signing & Capabilities and exclude architectures in Build Settings as shown below. Then, in example folder, runnpx react-native run-ios
To get a better understanding of how the example app is stuctured, what to do on onJoin, onTrack and onPeer listeners, creating PeerTrackNodes, how to use Redux, and what type of layouts and sorting you can implement in your app, checkout Example App's README
We have also implemented multiple views which are commonly used. Checkout the videos & relevant code in the Example app.
☝️ Minimum Configuration
- Support for Android API level 21 or higher
- Support for Java 8
- Support for iOS 10 or higher
- Support for React Native 0.63.3 or higher
- Xcode 12 or higher
🤝 Recommended Configuration
- Android API level 29 or higher
- Java 11 or higher
- iOS 15 or higher
- React Native 0.64.2 or higher
- Xcode 13 or higher
📱 Supported Devices
The Android SDK supports Android API level 21 and higher. It is built for armeabi-v7a, arm64-v8a, x86, and x86_64 architectures.
iPhone & iPads with iOS version 10 or higher.
Installation
npm install @100mslive/react-native-hms --save📲 Download the Sample iOS App here: https://testflight.apple.com/join/v4bSIPad
🤖 Download the Sample Android App here: https://appdistribution.firebase.dev/i/7b7ab3b30e627c35
🔐 Permissions
📱 For iOS Permissions
Add following lines in Info.plist file
<key>NSCameraUsageDescription</key>
<string>Please allow access to Camera to enable video conferencing</string>
<key>NSMicrophoneUsageDescription</key>
<string>Please allow access to Microphone to enable video conferencing</string>
<key>NSLocalNetworkUsageDescription</key>
<string>Please allow access to network usage to enable video conferencing</string>🤖 For Android Permissions
Add following permissions in AndroidManifest.xml
<uses-feature android:name="android.hardware.camera.autofocus"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />You will also need to request Camera and Record Audio permissions at runtime before you join a call or display a preview. Please follow Android Documentation for runtime permissions.
We suggest using react-native-permission to acquire permissions from both platforms.
QuickStart
The package exports all the classes and a HMSSDK class that manages everything.
Setting up the HMS Instance
first we'll have to call build method, that method returns an instance of HMSSDK class and the same is used to perform all the operations
import { HMSSDK } from '@100mslive/react-native-hms';
...
const hmsInstance = await HMSSDK.build();
// save this instance, it will be used for all the operations that we'll perform
...Add event listeners
add event listeners for all the events such as onPreview, onJoin, onPeerUpdate etc. the actions can be found in HMSUpdateListenerActions class
import { HMSUpdateListenerActions } from '@100mslive/react-native-hms';
...
// instance acquired from build() method
hmsInstance.addEventListener(
HMSUpdateListenerActions.ON_PREVIEW,
previewSuccess, // function that will be called on Preview success
);
...The event handlers are the way of handling any update happening in hms all events can be found in HMSUpdateListenerActions class
Error handling
import { HMSUpdateListenerActions } from '@100mslive/react-native-hms';
// add an error event listener
hmsInstance.addEventListener(HMSUpdateListenerActions.ON_ERROR, onError);Join the room
Joining the room connects you to the remote peer and broadcasts your stream to other peers, we need instance of HMSConfig in order to pass the details of room and user to join function.
NOTE: ON_JOIN listener should be added before calling join function to receive the event callback.
import { HMSUpdateListenerActions, HMSConfig } from '@100mslive/react-native-hms';
...
const HmsConfig = new HMSConfig({authToken, userID, roomID});
// instance acquired from build() method
hmsInstance.preview(HmsConfig); // to start preview
// or
hmsInstance.join(HmsConfig); // to join a room
...Calling various functions of HMS
// Mute Audio
hmsInstance?.localPeer?.localAudioTrack()?.setMute(true);
// Stop Video
hmsInstance?.localPeer?.localVideoTrack()?.setMute(true);
// Switch Camera
hmsInstance?.localPeer?.localVideoTrack()?.switchCamera();
// Leave the call (async function)
await hmsInstance?.leave();Viewing the video of a peer
To display a video on screen the 100ms package provides a UI component named HmsView that takes the video trackId and displays the video in that component.
HmsViewcomponent requireswidthandheightinstyleprop to set bounds of the tile that will show the video stream.One
HmsViewcomponent can only be connected with one videotrackId. To display multiple videos you have to create multiple instances ofHmsViewcomponent.Once the requirement of that
HmsViewis finshed it should be disposed.Every
HmsViewshould be unique, which should be done by passing akeyproperty and value as videotrackId.Recommended practice is to show maximum of 3 to 4
HmsViewon a single page/screen of the app. This avoids network data consumption & video decoding resources of the device.
...
import { HMSRemotePeer } from '@100mslive/react-native-hms';
// getting local track ID
const localTrackId: string = hmsInstance?.localPeer?.videoTrack?.trackId;
// getting remote track IDs
const remotePeers: HMSRemotePeer[] = hmsInstance?.remotePeers
const remoteVideoIds: string[] = [];
remotePeers.map((remotePeer: HMSRemotePeer) => {
const remoteTrackId: string = remotePeer?.videoTrack?.trackId;
if (remoteTrackId) {
remoteVideoIds.push(remoteTrackId);
}
});
...Display a video in HmsView
import { HMSVideoViewMode } from '@100mslive/react-native-hms';
// instance acquired from build() method
const HmsView = hmsInstance?.HmsView;
...
const styles = StyleSheet.create({
hmsView: {
height: '100%',
width: '100%',
},
});
// trackId should be acquired from the method explained above
// scaleType can be selected from HMSVideoViewMode as required
// mirror can be passed as true to flip videos horizontally
<HmsView style={styles.hmsView} trackId={trackId} mirror={true} scaleType={HMSVideoViewMode.ASPECT_FIT} />
...Mute/Unmute others
const mute: boolean = true;
// hms instance acquired by build methodhmsInstance?.changeTrackState(audioTrack as HMSTrack, mute);
hmsInstance?.changeTrackState(videoTrack as HMSTrack, mute);
const unmute: boolean = false;
await hmsInstance?.changeTrackState(audioTrack as HMSTrack, unmute);
await hmsInstance?.changeTrackState(videoTrack as HMSTrack, unmute);End Room for all
const reason = 'Host ended the room';
const lock = false; // optional parameter
// hms instance acquired by build method
await hmsInstance.endRoom(reason, lock);Remove Peer
import { HMSPeer } from '@100mslive/react-native-hms';
const reason = 'removed from room';
// hms instance acquired by build method
const peer: HMSPeer = hmsInstance?.remotePeers[0];
await hmsInstance.removePeer(peer, reason);Sending messages
import { HMSRole, HMSPeer } from '@100mslive/react-native-hms';
const message = 'hello'
const roles: HMSRole[] = hmsInstance?.knownRoles
// any remote peer
const peer: HMSPeer = hmsInstance?.remotePeers[0]
// send a different type of messages
await hmsInstance?.sendBroadcastMessage(message);
await hmsInstance?.sendGroupMessage(message, [role[0]);
await hmsInstance?.sendDirectMessage(message, peer);Role Change
import { HMSRole, HMSRemotePeer } from '@100mslive/react-native-hms';
// hms instance acquired by build method
const roles: HMSRole[] = hmsInstance?.knownRoles;
const newRole: HMSRole = roles[0];
// can any remote peer
const peer: HMSRemotePeer = hmsInstance?.remotePeers[0];
const force = false;
await hmsInstance.changeRole(peer, newRole, force); // request role change
await hmsInstance.changeRole(peer, newRole, !force); // force role changeRaise Hand & BRB
const parsedMetadata = JSON.parse(hmsInstance?.localPeer?.metadata);
// Raise Hand
// hms instance acquired by build method
await hmsInstance?.changeMetadata(
JSON.stringify({
...parsedMetadata,
isHandRaised: true,
})
);
// BRB
// hms instance acquired by build method
await hmsInstance?.changeMetadata(
JSON.stringify({
...parsedMetadata,
isBRBOn: true,
})
);HLS Streaming
import {
HMSHLSMeetingURLVariant,
HMSHLSConfig,
} from '@100mslive/react-native-hms';
const startHLSStreaming = () => {
// Default Settings
await hmsInstance.startHLSStreaming()
// Custom Settings
const hmsHLSMeetingURLVariant = new HMSHLSMeetingURLVariant({
meetingUrl: 'https://yogi.app.100ms.live/preview/nih-bkn-vek?skip_preview=true',
metadata: '',
});
const hmsHLSRecordingConfig = new HMSHLSRecordingConfig({
singleFilePerLayer: false,
videoOnDemand: false,
});
const hmsHLSConfig = new HMSHLSConfig({
hlsRecordingConfig: hmsHLSRecordingConfig,
meetingURLVariants: [hlsStreamingDetails],
});
await hmsInstance.startHLSStreaming(hmsHLSConfig)
.then(d => console.log('Start Hls Success: ', d))
.catch(e => console.log('Start Hls Error: ', e));
};Start Streaming / Recording
import { HMSRTMPConfig } from '@100mslive/react-native-hms';
const recordingDetails = HMSRTMPConfig({
record: true,
meetingURL: roomID + '/viewer?token=beam_recording',
rtmpURLs: [], // optional value
resolution: { height: 720, width: 1280 }, // optional value
// Resolution width
// Range is [500, 1280].
// Default value is 1280.
// If resolution height > 720 then max resolution width = 720.
// Resolution height
// Reange is [480, 1280].
// Default resolution width is 720.
// If resolution width > 720 then max resolution height = 720.
});
// hms instance acquired by build method
await hmsInstance?.startRTMPOrRecording(recordingDetails);Get RTC Stats
// hms instance acquired by build method
hmsInstance?.enableRTCStats();Screenshare
// hms instance acquired by build method
await hmsInstance?.startScreenshare();Getting Audio Levels for all speaking peers
import {
HMSUpdateListenerActions,
HMSSpeaker,
} from '@100mslive/react-native-hms';
// hms instance acquired by build method
hmsInstance?.addEventListener(HMSUpdateListenerActions.ON_SPEAKER, onSpeaker);
const onSpeaker = (data: HMSSpeaker[]) => {
data?.map((speaker: HMSSpeaker) =>
console.log('speaker audio level: ', speaker?.level)
);
};Local mute others
const remotePeer: HMSRemotePeer;
const isAudioPlaybackAllowed = remotePeer.remoteAudioTrack().setPlaybackAllowed(false);
const isVideoPlaybackAllowed = remotePeer.remoteVideoTrack().setPlaybackAllowed(true);
// hms instance acquired by build method
hmsInstance.setPlaybackForAllAudio(true) // mute
hmsInstance.setPlaybackForAllAudio(false) // unmuteLocally Set Volume
const volume: Float = 1.0;
const track: HMSTrack = remotePeer.audioTrack as HMSTrack;
// hms instance acquired by build method
hmsInstance?.setVolume(track, volume);Change Name
const newName: string = 'new name';
// hms instance acquired by build method
await hmsInstance.changeName(newName);Join with specific Track Settings
const getTrackSettings = () => {
let audioSettings = new HMSAudioTrackSettings({
maxBitrate: 32,
trackDescription: 'Simple Audio Track',
});
let videoSettings = new HMSVideoTrackSettings({
codec: HMSVideoCodec.vp8,
maxBitrate: 512,
maxFrameRate: 25,
cameraFacing: HMSCameraFacing.FRONT,
trackDescription: 'Simple Video Track',
resolution: new HMSVideoResolution({ height: 180, width: 320 }),
});
return new HMSTrackSettings({ video: videoSettings, audio: audioSettings });
};
const setupBuild = async () => {
const trackSettings = getTrackSettings();
const build = await HMSSDK.build({ trackSettings });
setInstance(build);
updateHms({ hmsInstance: build });
};Example Implementations
In the 100ms Example App we have shown how to setup the various listeners, what data to store in Redux and what all features you can implement.
We have also implemented multiple views which are commonly used. Checkout the videos & relevant code in the Example app.