Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is React Native Video?
3.
Installation and Setup
4.
Embedding Videos in React Native
5.
Props in React Native Video Player
6.
Playing Local Video Files in React Native
7.
Playing Remote Video Files in React Native
8.
External Video Controls in React Native
9.
Invoking Methods in Video Elements
10.
Frequently Asked Questions
10.1.
How does the React Native Video Player handle various video formats and resolutions?
10.2.
Is it feasible to add subtitles and closed captions to movies played using React Native Video Player?
10.3.
Why should one use the React Native Video Player for my mobile app?
11.
Conclusion
Last Updated: Mar 27, 2024
Medium

React Native Video Player

Author Ayush Mishra
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

React Native is an open-source mobile application framework that enables programmers to create cross-platform mobile apps using JavaScript and React. It has an open-source library, React Native Video Player, which offers many features and capabilities. It allows users to select between audio and text tracks, modify the rate, and support iOS and Android platforms.

React Native Video Player

In this blog, we will discuss React Native Video Player installation, embedding videos in react native, and playing local and remote video files using it.

What is React Native Video?

Reactive Native Video is a well-known open-source library for React Native, a platform for creating mobile applications, is React Native Video Player. It offers a customizable video player component that makes it simple for developers to control and integrate videos in their React Native projects. 

The library supports several video formats, provides playback controls, lets developers handle video events, and lets them alter the player's looks and actions. It makes it easier to incorporate videos into React Native applications and improves user interaction with multimedia content.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Installation and Setup

Users can use npm to set up the React Native Video Player package for their project. 

Run the following command in your terminal or command prompt, going to the root directory of your React Native project:

Command

npm install react-native-video-player


If you're using a Mac to run your native React application, use the following command as well:

npx pod-install

Embedding Videos in React Native

Users can use the built-in react-native-video component or the React Native Video Player module to embed videos in a React Native application. 

The steps to embed Video in React Native are as follows:-

Step 1: As stated in the previous section, install the package:

npm install react-native-video-player



Step 2: Add the VideoPlayer component to your React Native component by importing it:

import React from 'react';
import { View, StyleSheet } from 'react-native';
import VideoPlayer from 'react-native-video-player';


const VideoScreen = () => {
  return (
    <View style={styles.container}>
      <VideoPlayer
        video={{ uri: 'your_video_url_here.mp4' }}
        videoWidth={1200}
        videoHeight={600}
        resizeMode="contain"
        autoplay={false}
      />
    </View>
  );
};


const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});


export default VideoScreen;



Step 3: Your Video's URL or file path should be substituted for "your_video_url_here.mp4". To change the Video's dimensions, alter the style prop.

Props in React Native Video Player

The video player component in react-native-video-player offers several props so that you can modify its behavior and appearance. The following are some essential props you can use:

  • video: It is required props. The local file path or the video URL can be contained in an object with the URI field
     
  • videoWidth: The Video's original width. Set the player's aspect ratio using this prop
     
  • videoHeight: The Video's original height. Set the player's aspect ratio using this prop
     
  • paused: Set the value of paused to true to pause the Video
     
  • defaultMuted: Set to true to mute the Video automatically
     
  • autoplay: When set to true, the Video will begin to play as soon as the component is mounted
     
  • controlsTimeout: The amount of time in milliseconds (in which the controls for the Video will automatically disappear)
     
  • hideControlsOnStart: If set to true, the controls will be hidden when the Video begins to play
     
  • disableFullscreen: If set to true, the fullscreen button will be disabled
     
  • disableSeek: Set to true to prevent dragging the seek bar to advance the Video
     
  • disableVolume: When set to true, the volume control is turned off
     
  • disableBack: Set to true to remove Android's back button
     
  • onEnterFullscreen: A function is invoked when fullscreen mode is activated
     
  • onExitFullscreen: The function that is called when fullscreen mode is ended
     
  • allowsExternalPlayback (iOS only): When set to true, this prop enables external devices like AirPlay or HDMI to control the Video. It only applies to iOS devices.
     
  • controls: This prop displays the built-in video player controls when it is set to true, allowing users to manage video playing via functions like play, pause, seek, volume control, etc

Playing Local Video Files in React Native

Users must make sure that the video files are included with your React Native app and accessible through the app's assets in order for react-native-video-player to play local video files. 

The steps to play local video files are:-

Step 1: The video files should be added to your app's assets. Create a new folder in your project directory, such as assets/videos. Put your video files in the assets/videos folder (.mp4,.mov, etc.).


Step 2: Update the settings for your React Native project (for Expo or React Native CLI):

Expo: If you're using Expo, no additional configuration is required. Expo manages the assets for you automatically.

React Native CLI: To use React Native CLI, you must add the assets to the react-native.config.js file in the project's root. React Native.config.js file should be updated with the following code:

module.exports = {
  assets: ['./assets/videos'],
};



Step 3: Import the video files using the require() function to get the correct file path.

<VideoPlayer
        video={require('./assets/videos/your_video_file.mp4')}
        videoWidth={300}
        videoHeight={200}
        resizeMode="contain"
        controls={true}
      />



Step 4: 'Your_Video_File.mp4' should be changed to the name of the local video file you placed in the assets/videos folder.

Playing Remote Video Files in React Native

React-native-video-player's remote video URLs are video URLs that lead to videos that are stored on remote servers or internet platforms. These URLs are used in the Video component's source prop to define where the Video will be played.


 <VideoPlayer
        video={{ uri: 'https://example.com/your_video_url_here.mp4' }}
        videoWidth={200}
        videoHeight={200}
        resizeMode="contain"
        controls={true}
      />


Import the video files using the require() function to get the correct file path. The exact URL of the remote Video you want to play should be substituted for "https://example.com/your_video_url_here.mp4". A proper video file accessed online should be the URL's target.

External Video Controls in React Native

Custom user interface elements must be implemented to control the playback of external video controls. Instead of interacting with the Video using the built-in controls offered by the video player component, Users create and maintain their own set of buttons, sliders, and other elements.

Code

import React, { useState, useRef } from 'react';
import { View, StyleSheet, Button } from 'react-native';
import Video from 'react-native-video';


const App = ({ video }) => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [isMuted, setIsMuted] = useState(false);
  const videoRef = useRef(null);


  const togglePlaying = () => {
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.pause();
      } else {
        videoRef.current.play();
      }
      setIsPlaying(!isPlaying);
    }
  };


  return (
    <View>
      < Video
        ref={videoRef}
        source={video}
        paused={!isPlaying}
        controls={false} // Hide built-in controls since we are using external controls
        style={styles.backgroundVideo}
        muted={isMuted}
      />
      <Button onPress={togglePlaying} title={isPlaying ? 'Stop' : 'Play'} />
      <Button
        onPress={() => setIsMuted(m => !m)}
        title={isMuted ? 'Unmute' : 'Mute'}
      />
    </View>
  );
};


const styles = StyleSheet.create({
  backgroundVideo: {
    width: 300,
    height: 200,
  },
});


export default App;

Invoking Methods in Video Elements

Users may use the video reference to access the methods in the video element when using react-native-video. By doing this, you can utilize methods like play, pause, seek, etc., to control the video playing by the needs of your program.

Code

import React, { useRef } from 'react';
import { View, StyleSheet } from 'react-native';
import Video from 'react-native-video';
import video from '../test-video.mp4';


const video_component= () => {
    const videoPlayer = React.useRef();


    const goScreen = () => {  
        if (videoPlayer.current) {  
            videoPlayer.current.presentFullscreenPlayer();  
        }  
    };


    return (
        < Video  
            ref={ref => (videoPlayer.current = ref)}
            source={video}                 
            paused={false}                
            style={styles.backgroundVideo}  
            repeat={true}                  
        />
    )
}


Explanation

First, import the video file and the required modules. To construct a reference called videoPlayer, we employ the useRef hook. We create a function called goFullScreen that enables full-screen playback on video players. The goFullScreen method is called when necessary, and the Video component is rendered along with the video file. The Video starts automatically and loops repeatedly.

Frequently Asked Questions

How does the React Native Video Player handle various video formats and resolutions?

React Native Player supports popular video formats like MP4, MOV, and HLS. Encode videos in multiple resolutions for compatibility with devices and screen sizes. The player adjusts video quality based on network conditions, ensuring smooth playback.

Is it feasible to add subtitles and closed captions to movies played using React Native Video Player?

React Native Video Player supports closed captions and subtitles, allowing multilingual support and accessibility features. Subtitle files in formats like WebVTT and SRT can be provided for added accessibility and multilingual support.

Why should one use the React Native Video Player for my mobile app?

React Native Video Player simplifies video integration into mobile apps, offering seamless streaming, compatibility for multiple formats, and programmable controls. It accelerates development by addressing video playback issues, resulting in a great media experience for app users.

Conclusion

React Native apps integrate video playback features efficiently due to the robust and adaptable React Native Video Player component. It offers an effective approach for giving users of iOS and Android smartphones interesting multimedia experiences.

We hope this blog has helped you enhance your knowledge of React Native Video Player. Do not stop learning! We recommend you read some of our React native articles: 

 

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

You can also consider our React Js Course to give your career an edge over others.

We wish you Good Luck! 

Happy Learning!

Previous article
React Native Image
Next article
Alert in React Native
Live masterclass