Try Live Demo

ReactJS is one of the most popular JavaScript frameworks used to power extremely dynamic web applications. By building a ReactJS component, we can develop powerful applications that seamlessly integrate Ant Media Server into React, making it more versatile and engaging.

While Ant Media offers an array of Software Development Kits (SDKs), for React applications, the JavaScript SDK is the ideal choice. In this guide, we will take you through a step-by-step process of harnessing the capabilities of the Ant Media JavaScript SDK in conjunction with React.

Our focus will be on publishing a WebRTC stream, covering all the essential setup steps such as importing dependencies, initializing the SDK, handling publishing events, and designing a user-friendly interface for the ReactJS component.

Let’s dive into the tutorial and get started with integrating Ant Media JavaScript SDK into your ReactJS project!

Prerequisites

Before getting started, make sure you have the following prerequisites:

  • Node.js installed on your machine
  • Basic knowledge of React and JavaScript

Full Code is Available on Github.

Step 1: Create a New ReactJS Project

Start by creating a new ReactJS project using Create React App. Open your terminal and run the following command:

npx create-react-app ant-media-streaming

This command will create a new directory named ant-media-streaming with a basic React project structure.

Step 2: Install Dependencies

Navigate to the project directory and install the required dependencies. Run the following command:

cd ant-media-streaming
npm i @antmedia/webrtc_adaptor 
npm i bootstrap react-bootstrap

This command will install the Ant Media JS SDK, Bootstrap, and React Bootstrap packages.

Step 3: Create the ReactJS Component

Inside the src directory, create a new file named PublishingComponent.js. This file will contain the code for the publishing component. Open PublishingComponent.js and add the following code:

Full Code is Available on Github.

Understanding the code

Full Code is Available on Github.

Part 1: Importing Dependencies

import React, { useState, useEffect, useRef } from 'react';
import { Button, Container, Row, Col } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import { WebRTCAdaptor } from '@antmedia/webrtc_adaptor';

At the top of this ReactJS component, we import the necessary dependencies for our component. These include React, the useState, useEffect, and useRef hooks, Bootstrap components (Button, Container, Row, and Col), the Bootstrap CSS, and the WebRTCAdaptor from the Ant Media JS SDK.

We imported WebRTCAdaptor from the JS SDK which will act as an interface for us to publish and play streams from Ant Media Server

Part 2: Defining the Publishing Component

const PublishingComponent = () => {
  const [publishing, setPublishing] = useState(false);
  const [websocketConnected, setWebsocketConnected] = useState(false);
  const [streamId, setStreamId] = useState('stream123');

  const webRTCAdaptor = useRef(null);
  var publishedStreamId = useRef(null);

  // ... Rest of the component code ...
}

Here we define the PublishingComponent functional component. Inside this ReactJS component, we use the useState hook to create state variables: publishing, websocketConnected, and streamId. These variables will manage the publishing state, WebSocket connection status, and the entered stream ID, respectively.

We also create a webRTCAdaptor ref using the useRef hook. This ref will hold an instance of the WebRTCAdaptor class from the Ant Media JS SDK.

Part 3: Handling Publishing Events

const handlePublish = () => {
  publishedStreamId.current=streamId
  setPublishing(true);
  webRTCAdaptor.current.stop(streamId);
};

const handleStopPublishing = () => {
  setPublishing(false);
  webRTCAdaptor.current.stop(publishedStreamId.current);
};

const handleStreamIdChange = (event) => {
  setStreamId(event.target.value);
};

Next we define the event handler functions for publishing, stopping publishing, and stream ID change events. The handlePublish function sets the publishing state to true and calls the publish method of the webRTCAdaptor ref with the streamId.

The handleStopPublishing function sets the publishing state to false and calls the stop method of the webRTCAdaptor ref with the publishedStreamId.

The handleStreamIdChange function is triggered when the value of the stream ID input field changes. It updates the streamId state with the new value.

Part 4: Initializing WebRTC Adaptor

Note : Please Change The Ant Media IP in the WebRTCAdaptor Initialization

useEffect(() => {
    webRTCAdaptor.current = new WebRTCAdaptor({
      websocket_url: 'wss://AMS_IP:/WebRTCAppEE/websocket',
      mediaConstraints: {
        video: true,
        audio: true,
      },
      peerconnection_config: {
        iceServers: [{ urls: 'stun:stun1.l.google.com:19302' }],
      },
      sdp_constraints: {
        OfferToReceiveAudio: false,
        OfferToReceiveVideo: false,
      },
      localVideoId: 'localVideo',
      callback: (info, obj) => {
        if (info === 'initialized') {
          setWebsocketConnected(true);
        }
        console.log(info, obj);
      },
      callbackError: function (error, message) {
        console.log(error, message);
      },
    });
}, []);

To initialize the webRTCAdaptor, we’ll use the useEffect hook.

Step 4: Update the App Component

Open the src/App.js file and replace its content with the following code:

In the above code, we import the PublishingComponent and render it inside the App component.

Step 5: Run the Application

Save all the changes, and in your terminal, run the following command inside the project directory:

npm start

This command will start the development server, and you can view the application in your browser at http://localhost:3000. You should see the “Live Streaming” heading, a video element for displaying the local video stream, an input field for entering the stream ID, and a “Start Publishing” button.

Play Component

The ReactJS component built for playing the live stream is available here. The Play and Publish components are designed separately, but for the sake of simplicity they can be merged together if preferred.

  1. To use the player page, create a new component file called PlayingComponent.js and add the following code, which is available here.
  2. Update the root ReactJS component to import the new play component as in the example below.
  3. Run the npm start command in the directory.
import PlayingComponent from './PlayingComponent';

const App = () => {
  return (
    <div>
      <PlayingComponent />
    </div>
  );
};
Play Reactjs Component
Player Page

Conclusion

We hope this tutorial has provided you with a comprehensive guide to getting started with the Ant Media JavaScript SDK and ReactJS components.

Live streaming opens up a world of possibilities for interactive and engaging applications, and with the right tools at your disposal, you can bring your ideas to life.

Now it’s your turn to start exploring the exciting realm of live streaming with the Ant Media JavaScript SDK and React.

Unleash your creativity, build innovative applications, and deliver immersive real-time experiences to your audience by starting a free trial and getting started with Ant Media Server.

Happy live streaming!

Categories: Tutorial

Usama Tahseen

Usama is a Software Engineer at Ant Media. His technical stack includes WebRTC, Gstreamer , FFmpeg , Python, Javascript, Node.js

chatsimple