Skip to main content
Version: 1.x.x

Quick Start for Http Live Streaming(HLS) in React Native

VideoSDK empowers you to seamlessly integrate the Http Live Streaming(HLS) feature into your React Native application within minutes.

In this quickstart, you'll explore this feature of VideoSDK. Follow the step-by-step guide to integrate it within your application.

info

For low-latency interactive live streaming (under 100ms), follow this documentation.

Prerequisites

Before proceeding, ensure that your development environment meets the following requirements:

  • Video SDK Developer Account (Not having one, follow Video SDK Dashboard)
  • Basic understanding of React Native
  • Node.js >= 22.11.0
  • NPM v10+ (comes installed with newer Node versions)
  • Android Studio or Xcode installed
important

One should have a VideoSDK account to generate token. Visit VideoSDK dashboard to generate token

App Architecture

The App will contain the following screens:

  1. Join Screen : This screen allows the SPEAKER to create a studio or join a predefined studio, and SIGNALLING_ONLY to join a predefined studio.

  2. Speaker Screen : This screen contains the list of speakers and studio controls, such as enabling/disabling the microphone and camera, and leaving the studio.

  3. Viewer Screen : This screen includes a live stream player where viewers can watch the stream.

Getting Started with the Code!

Create App

Create a new React Native App using the below command.

npx @react-native-community/cli init AppName

For React Native setup, you can follow the Official Documentation.

Install VideoSDK and Dependencies

Install the VideoSDK along with @react-native-clipboard/clipboard (used to copy the meeting id) and react-native-safe-area-context (used to render the app within the device's safe area). Ensure that you are in your project directory before running this command.

npm install "@videosdk.live/react-native-sdk"  "@videosdk.live/react-native-incallmanager" "@react-native-clipboard/clipboard" "react-native-safe-area-context"

Project Structure

Directory Structure
  root
├── node_modules
├── android
├── ios
├── App.js
├── api.js
├── index.js

Project Configuration

Android Setup

AndroidManifest.xml
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cool.app"
>
<!-- Give all the required permissions to app -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Needed to communicate with already-paired Bluetooth devices. (Legacy up to Android 11) -->
<uses-permission
android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.BLUETOOTH_ADMIN"
android:maxSdkVersion="30" />

<!-- Needed to communicate with already-paired Bluetooth devices. (Android 12 upwards)-->
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
</manifest>
android/app/build.gradle
  dependencies {
implementation project(':rnwebrtc')
}
android/settings.gradle
include ':rnwebrtc'
project(':rnwebrtc').projectDir = new File(rootProject.projectDir, '../node_modules/@videosdk.live/react-native-webrtc/android')
MainApplication.kt
import live.videosdk.rnwebrtc.WebRTCModulePackage

class MainApplication : Application(), ReactApplication {

override val reactHost: ReactHost by lazy {
getDefaultReactHost(
context = applicationContext,
packageList =
PackageList(this).packages.apply {
// Packages that cannot be autolinked yet can be added manually here, for example:
// add(MyReactNativePackage())
add(WebRTCModulePackage())
},
)
}

override fun onCreate() {
super.onCreate()
loadReactNative(this)
}
}
note

This MainApplication.kt matches the template of recent React Native versions — verified against the React Native 0.87 template that npx @react-native-community/cli init currently produces. On an older React Native version, add WebRTCModulePackage() to the package list in your project's existing MainApplication file instead — for example inside getPackages() in the Java template.

iOS Setup

To update CocoaPods, you can reinstall the gem using the following command:

$ sudo gem install cocoapods

Select Your_Xcode_Project/TARGETS/BuildSettings, in Header Search Paths, add "$(SRCROOT)/../node_modules/@videosdk.live/react-native-incall-manager/ios/RNInCallManager"

Podfile
pod 'react-native-webrtc', :path => '../node_modules/@videosdk.live/react-native-webrtc'
note

Your Podfile's default platform :ios, min_ios_version_supported line already satisfies react-native-webrtc's minimum iOS requirement.

You need to install the pods by running the following command:

pod install

Add the following lines to your info.plist file located at (project folder/ios/projectname/info.plist):

ios/projectname/info.plist
<key>NSCameraUsageDescription</key>
<string>Camera permission description</string>
<key>NSMicrophoneUsageDescription</key>
<string>Microphone permission description</string>

Register Service

Register VideoSDK services in your root index.js file for the initialization service.

index.js
import { AppRegistry } from "react-native";
import App from "./App";
import { name as appName } from "./app.json";
import { register } from "@videosdk.live/react-native-sdk";

register();

AppRegistry.registerComponent(appName, () => App);

Step 1: Get started with API.js

Prior to moving on, you must create an API request to generate a unique meetingId. You will need an authentication token, which you can create either through the videosdk-rtc-api-server-examples or directly from the VideoSDK Dashboard for developers.

api.js
// Generate your token at https://app.videosdk.live/api-keys and paste it below.
export const authToken = "";

// API call to create meeting
export const createMeeting = async ({ token }) => {
try {
const res = await fetch(`https://api.videosdk.live/v2/rooms`, {
method: "POST",
headers: {
authorization: `${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({}),
});

if (!res.ok) {
throw new Error(`Failed to create meeting: ${res.status}`);
}

//Destructuring the roomId from the response
const { roomId } = await res.json();
return roomId;
} catch (error) {
console.error("createMeeting failed", error);
throw error;
}
};

Step 2: Wireframe App.js with all the components

To build up wireframe of App.js, you need to use VideoSDK Hooks and Context Providers. VideoSDK provides MeetingProvider, MeetingConsumer, useMeeting and useParticipant hooks.

First you need to understand Context Provider and Consumer. Context is primarily used when some data needs to be accessible by many components at different nesting levels.

  • MeetingProvider: This is the Context Provider. It accepts value config and token as props. The Provider component accepts a value prop to be passed to consuming components that are descendants of this Provider. One Provider can be connected to many consumers. Providers can be nested to override values deeper within the tree.
  • MeetingConsumer: This is the Context Consumer. All consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes.
  • useMeeting: This is the meeting hook API. It includes all the information related to meeting such as join, leave, toggle mic or webcam etc.
  • useParticipant: This is the participant hook API. It is responsible for handling all the events and props related to one particular participant such as name, webcamStream, micStream etc.

From v1.0.0, all these methods are asynchronous and return a Promise, so await them and handle failures with try / catch. For details, see the Migration Guide.

The Meeting Context provides a way to listen for any changes that occur when a participant joins the meeting or makes modifications to their microphone, camera, and other settings.

Begin by making a few changes to the code in the App.js file.

App.js
import React, { useState, useMemo, useRef, useEffect } from "react";
import {
TouchableOpacity,
Text,
TextInput,
View,
FlatList,
} from "react-native";
import {
MeetingProvider,
useMeeting,
useParticipant,
MediaStream,
RTCView,
Constants,
} from "@videosdk.live/react-native-sdk";
import Clipboard from "@react-native-clipboard/clipboard";
import { createMeeting, authToken } from "./api";
import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context";

// Responsible for either scheduling a new meeting or joining an existing one as a host or as a viewer.
function JoinScreen({ getMeetingAndToken, setMode }) {
return null;
}

// Responsible for managing participant video stream
function ParticipantView(props) {
return null;
}

// Responsible for managing meeting controls such as toggle mic / webcam and leave
function Controls() {
return null;
}

// Responsible for Speaker side view, which contains Meeting Controls(toggle mic/webcam & leave) and Participant list
function SpeakerView() {
return null;
}

// Responsible for Viewer side view, which contains video player for streaming HLS and managing HLS state (HLS_STARTED, HLS_STOPPING, HLS_STARTING, etc.)
function ViewerView() {
return null;
}

// Responsible for managing two views (Speaker & Viewer) based on provided mode (`SEND_AND_RECV` & `SIGNALLING_ONLY`)
function Container(props) {
return null;
}

function AppContent() {
const [meetingId, setMeetingId] = useState(null);

//State to handle the mode of the participant i.e. SEND_AND_RECV or SIGNALLING_ONLY
const [mode, setMode] = useState("SEND_AND_RECV");

//Getting MeetingId from the API created earlier
const getMeetingAndToken = async (id) => {
if (!authToken) {
console.error("PLEASE PROVIDE TOKEN IN api.js FROM app.videosdk.live");
return;
}
const meetingId =
id == null ? await createMeeting({ token: authToken }) : id;
setMeetingId(meetingId);
};

return authToken && meetingId ? (
<MeetingProvider
config={{
meetingId,
micEnabled: true,
webcamEnabled: true,
name: "C.V. Raman",
//This will be the mode of the participant SEND_AND_RECV or SIGNALLING_ONLY
mode: mode,
defaultCamera: "front",
}}
token={authToken}
>
<Container />
</MeetingProvider>
) : (
<JoinScreen getMeetingAndToken={getMeetingAndToken} setMode={setMode} />
);
}

function App() {
return (
<SafeAreaProvider>
<AppContent />
</SafeAreaProvider>
);
}

export default App;

Step 3: Implement Join Screen

Join screen will work as medium to either schedule a new meeting or to join an existing one as a host or as a viewer.

This functionality will have 3 buttons:

1. Join as Host: When this button is clicked, the person will join the meeting with the entered meetingId as HOST.

2. Join as Viewer: When this button is clicked, the person will join the meeting with the entered meetingId as SIGNALLING_ONLY.

3. Create Studio Room: When this button is clicked, the person will join a new meeting as HOST.

JoinScreen Component
function JoinScreen({ getMeetingAndToken, setMode }) {
const [meetingVal, setMeetingVal] = useState("");

const JoinButton = ({ value, onPress }) => {
return (
<TouchableOpacity
style={{
backgroundColor: "#1178F8",
padding: 12,
marginVertical: 8,
borderRadius: 6,
}}
onPress={onPress}
>
<Text style={{ color: "white", alignSelf: "center", fontSize: 18 }}>
{value}
</Text>
</TouchableOpacity>
);
};
return (
<SafeAreaView
style={{
flex: 1,
backgroundColor: "black",
justifyContent: "center",
paddingHorizontal: 6 * 10,
}}
>
<TextInput
value={meetingVal}
onChangeText={setMeetingVal}
placeholder={"XXXX-XXXX-XXXX"}
placeholderTextColor={"grey"}
style={{
padding: 12,
borderWidth: 1,
borderColor: "white",
borderRadius: 6,
color: "white",
marginBottom: 16,
}}
/>
<JoinButton
onPress={() => {
getMeetingAndToken(meetingVal);
}}
value={"Join as Host"}
/>
<JoinButton
onPress={() => {
setMode("SIGNALLING_ONLY");
getMeetingAndToken(meetingVal);
}}
value={"Join as Viewer"}
/>
<Text
style={{
alignSelf: "center",
fontSize: 22,
marginVertical: 16,
fontStyle: "italic",
color: "grey",
}}
>
---------- OR ----------
</Text>

<JoinButton
onPress={() => {
getMeetingAndToken();
}}
value={"Create Studio Room"}
/>
</SafeAreaView>
);
}

Output

Step 4: Implement Container Component

Next step is to create a container to manage Join screen, SpeakerView and ViewerView components based on the mode.

You need to determine the mode of the localParticipant, if its SEND_AND_RECV, display the SpeakerView component otherwise show the ViewerView component.

Container Component
function Container() {
const { join, localParticipant } = useMeeting({
onError: (error) => {
console.log(error.message);
},
});

return (
<View style={{ flex: 1 }}>
{localParticipant?.mode == Constants.modes.SEND_AND_RECV ? (
<SpeakerView />
) : localParticipant?.mode == Constants.modes.SIGNALLING_ONLY ? (
<ViewerView />
) : (
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "black",
}}
>
<Text style={{ fontSize: 20, color: "white" }}>
Press Join button to enter studio.
</Text>
<Button
btnStyle={{
marginTop: 8,
paddingHorizontal: 22,
padding: 12,
borderWidth: 1,
borderColor: "white",
borderRadius: 8,
}}
buttonText={"Join"}
onPress={async () => {
try {
await join();
} catch (error) {
console.error("Failed to join meeting", error);
}
}}
/>
</View>
)}
</View>
);
}

// Common Component which will also be used in Controls Component
const Button = ({ onPress, buttonText, backgroundColor, btnStyle }) => {
return (
<TouchableOpacity
onPress={onPress}
style={{
...btnStyle,
backgroundColor: backgroundColor,
padding: 10,
borderRadius: 8,
}}
>
<Text style={{ color: "white", fontSize: 12 }}>{buttonText}</Text>
</TouchableOpacity>
);
};

Output

Step 5: Implement SpeakerView

Next step is to create SpeakerView and Controls components to manage features such as join, leave, mute and unmute.

  1. You have to retrieve all the participants using the useMeeting hook and filter them based on the mode set to SEND_AND_RECV ensuring that only Speakers are displayed on the screen.
SpeakerView
function SpeakerView() {
// Get the Participant Map and meetingId
const { meetingId, participants } = useMeeting({});

// For getting speaker participant, filter out `SEND_AND_RECV` mode participant
const speakers = useMemo(() => {
const speakerParticipants = [...participants.values()].filter(
(participant) => {
return participant.mode == Constants.modes.SEND_AND_RECV;
}
);
return speakerParticipants;
}, [participants]);

return (
<SafeAreaView style={{ backgroundColor: "black", flex: 1 }}>
{/* Render Header for copy meetingId and leave meeting*/}
<HeaderView />

{/* Render Participant List */}
{speakers.length > 0 ? (
<FlatList
data={speakers}
renderItem={({ item }) => {
return <ParticipantView participantId={item.id} />;
}}
/>
) : null}

{/* Render Controls */}
<Controls />
</SafeAreaView>
);
}

function HeaderView() {
const { meetingId, leave } = useMeeting();
return (
<View
style={{
flexDirection: "row",
marginTop: 12,
justifyContent: "space-evenly",
alignItems: "center",
}}
>
<Text style={{ fontSize: 24, color: "white" }}>{meetingId}</Text>
<Button
btnStyle={{
borderWidth: 1,
borderColor: "white",
}}
onPress={() => {
Clipboard.setString(meetingId);
alert("MeetingId copied successfully");
}}
buttonText={"Copy MeetingId"}
backgroundColor={"transparent"}
/>
<Button
onPress={async () => {
try {
await leave();
} catch (error) {
console.error("Failed to leave meeting", error);
}
}}
buttonText={"Leave"}
backgroundColor={"#FF0000"}
/>
</View>
);
}

function Container(){
...

const mMeeting = useMeeting({
onMeetingJoined: async () => {
// Pin the local participant if he joins in SEND_AND_RECV mode
if (mMeetingRef.current.localParticipant.mode === "SEND_AND_RECV") {
try {
await mMeetingRef.current.localParticipant.pin();
} catch (error) {
console.error("Failed to pin the local participant", error);
}
}
},
onError: (error) => {
console.log(error.message);
},
});

// Create a ref to meeting object so that when used inside the
// Callback functions, meeting state is maintained
const mMeetingRef = useRef(mMeeting);
useEffect(() => {
mMeetingRef.current = mMeeting;
}, [mMeeting]);

return <>...</>;
}
  1. You need to then create the ParticipantView to display the participant's media. To play the media, use the webcamStream and micStream from the useParticipant hook.
ParticipantView
function ParticipantView({ participantId }) {
const { webcamStream, webcamOn } = useParticipant(participantId);
return webcamOn && webcamStream ? (
<RTCView
streamURL={new MediaStream([webcamStream.track]).toURL()}
objectFit={"cover"}
style={{
height: 300,
marginVertical: 8,
marginHorizontal: 8,
}}
/>
) : (
<View
style={{
backgroundColor: "grey",
height: 300,
justifyContent: "center",
alignItems: "center",
marginVertical: 8,
marginHorizontal: 8,
}}
>
<Text style={{ fontSize: 16 }}>NO MEDIA</Text>
</View>
);
}
  1. You have to add the Controls component which will allow the speaker to toggle their media and start/stop HLS.
Controls Component
function Controls() {
const { toggleWebcam, toggleMic, startHls, stopHls, hlsState } = useMeeting(
{}
);

const _handleHLS = async () => {
try {
if (!hlsState || hlsState === "HLS_STOPPED") {
await startHls({
layout: {
type: "GRID",
priority: "PIN",
gridSize: 4,
},
theme: "DARK",
orientation: "portrait",
});
} else if (hlsState === "HLS_STARTED" || hlsState === "HLS_PLAYABLE") {
await stopHls();
}
} catch (error) {
console.error("Failed to toggle HLS", error);
}
};

return (
<View
style={{
padding: 24,
flexDirection: "row",
justifyContent: "space-between",
}}
>
<Button
onPress={async () => {
try {
await toggleWebcam();
} catch (error) {
console.error("Failed to toggle webcam", error);
}
}}
buttonText={"Toggle Webcam"}
backgroundColor={"#1178F8"}
/>
<Button
onPress={async () => {
try {
await toggleMic();
} catch (error) {
console.error("Failed to toggle mic", error);
}
}}
buttonText={"Toggle Mic"}
backgroundColor={"#1178F8"}
/>
{hlsState === "HLS_STARTED" ||
hlsState === "HLS_STOPPING" ||
hlsState === "HLS_STARTING" ||
hlsState === "HLS_PLAYABLE" ? (
<Button
onPress={() => {
_handleHLS();
}}
buttonText={
hlsState === "HLS_STARTED"
? `Live Starting`
: hlsState === "HLS_STOPPING"
? `Live Stopping`
: hlsState === "HLS_PLAYABLE"
? `Stop Live`
: `Loading...`
}
backgroundColor={"#FF5D5D"}
/>
) : (
<Button
onPress={() => {
_handleHLS();
}}
buttonText={`Go Live`}
backgroundColor={"#1178F8"}
/>
)}
</View>
);
}

Output Of SpeakerView Component

Step 6: Implement ViewerView

When the HOST (SEND_AND_RECV mode participant) initiates the live streaming, viewers will be able to watch it.

To implement the player view, you have to use react-native-video. It will be helpful for playing the HLS stream.

Begin by adding this package.

npm install react-native-video

With react-native-video installed, you can now get the hlsUrls and isHlsPlayable from the useMeeting hook which will be used to play the HLS in the player.

// imports react-native-video
import Video from "react-native-video";

function ViewerView({}) {
const { hlsState, hlsUrls } = useMeeting();

return (
<SafeAreaView style={{ flex: 1, backgroundColor: "black" }}>
{hlsState == "HLS_PLAYABLE" ? (
<>
{/* Render Header for copying the meetingId and leaving meeting*/}
<HeaderView />

{/* Render VideoPlayer that will play `playbackHlsUrl`*/}
<Video
controls={true}
source={{
uri: hlsUrls.playbackHlsUrl,
}}
resizeMode={"contain"}
style={{
flex: 1,
backgroundColor: "black",
}}
onError={(e) => console.log("error", e)}
/>
</>
) : (
<SafeAreaView
style={{ flex: 1, justifyContent: "center", alignItems: "center" }}
>
<Text style={{ fontSize: 20, color: "white" }}>
HLS is not started yet or is stopped
</Text>
</SafeAreaView>
)}
</SafeAreaView>
);
}

Output of ViewerView Component

tip

Stuck anywhere? Check out this example code on GitHub

Got a Question? Ask us on discord