Create a Video Player App using React-Native
Last Updated :
02 Aug, 2024
React-Native is an open-source JavaScript framework used to broaden cross-platform packages i.e., you may write code in React-Native and publish it as an Android or IOS app. In this article, we will build a Video Player app with the usage of React-Native. The app will run on both Android and IOS.
Preview of the Final Output: Let us have a look at how the final application will look like.
Video Player AppPrerequisites
Approach to create Video PLayer App
The app contains two buttons Play/Pause button and Open Video button. We use expo-document-picker package to select the vide file. We mention type as mp4 so that only mp4 files are selected. This can be called using the function DocumentPicker.getDocumentAsync({ type: 'video/mp4' }); For playing the video, we use expo-av package. The basic video player app can play any mp4 video.
Steps to create our Video Player App
Step 1: Create a React Native app by using this command:
npx create-expo-app VideoPlayerApp
Step 2: Navigate to our project through this command:
cd VideoPlayerApp
Step 3: To add the required dependencies use the below command :
npm install @react-navigation/native @react-navigation/stack expo-av expo-document-picker
Project Structure:
Project StructureThe updated dependencies in package.json file will look like this:
"dependencies": {
"expo-av": "~13.2.1",
"expo-camera": "~13.2.1",
"expo-status-bar": "~1.4.4",
"expo-permissions": "~14.1.1",
"@expo/vector-icons": "^13.0.0",
"expo-media-library": "~15.2.3",
"react-native-paper": "4.9.2",
"expo-document-picker": "~11.2.2",
"react-native-screens": "~3.20.0",
"@react-navigation/stack": "^6.3.20",
"@react-navigation/native": "6.0.0",
"react-native-gesture-handler": "~2.9.0",
"@react-navigation/bottom-tabs": "^6.5.11",
"react-native-safe-area-context": "4.5.0"
}
Example: Write the following code in the respective files:
JavaScript
// App.js
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import VideoPlayer from './VideoPlayer';
const Stack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Video Player App" component={VideoPlayer} />
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
JavaScript
// VideoPlayer.js
import React, { useState, useEffect } from 'react';
import { View, TouchableOpacity, Text } from 'react-native';
import { Video } from 'expo-av';
import * as DocumentPicker from 'expo-document-picker';
import VideoPlayerStyles from './VideoPlayerStyles';
const styles = VideoPlayerStyles;
const VideoPlayer = () => {
const [videoStatus, setVideoStatus] = useState({});
const [videoUri, setVideoUri] = useState(null);
const videoRef = React.useRef(null);
useEffect(() => {
const currentVideoRef = videoRef.current;
return () => {
videoStatus.isPlaying && currentVideoRef && currentVideoRef.pauseAsync();
};
}, [videoStatus]);
const togglePlayPause = async () => {
if (videoRef.current) {
if (videoStatus.isPlaying) {
await videoRef.current.pauseAsync();
} else {
await videoRef.current.playAsync();
}
setVideoStatus((prevStatus) => ({ isPlaying: !prevStatus.isPlaying }));
}
};
const openVideoPicker = async () => {
try {
const result = await DocumentPicker.getDocumentAsync({ type: 'video/*' });
if (result.type === 'success' && result.uri) {
setVideoUri(result.uri);
setVideoStatus({ isPlaying: false });
}
} catch (error) {
console.error('Error picking video:', error);
}
};
return (
<View style={styles.container}>
{videoUri ? (
<Video
ref={videoRef}
source={{ uri: videoUri }}
style={styles.video}
resizeMode="contain"
shouldPlay={videoStatus.isPlaying}
isLooping
useNativeControls
/>
) : (
<Text style={styles.noVideoText}>No video selected</Text>
)}
<TouchableOpacity onPress={togglePlayPause} disabled={!videoUri}>
<Text style={styles.playPauseButton}>{videoStatus.isPlaying ? 'Pause' : 'Play'}</Text>
</TouchableOpacity>
<TouchableOpacity onPress={openVideoPicker}>
<Text style={styles.openVideoButton}>Open Video</Text>
</TouchableOpacity>
</View>
);
};
export default VideoPlayer;
JavaScript
// VideoPlayerStyles.js
import { StyleSheet } from 'react-native';
export default VideoPlayerStyles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
video: {
width: 300,
height: 200,
marginBottom: 20,
},
noVideoText: {
fontSize: 16,
color: 'gray',
marginBottom: 20,
},
playPauseButton: {
fontSize: 18,
color: 'blue',
fontWeight: 'bold',
marginBottom: 10,
},
openVideoButton: {
fontSize: 18,
color: 'green',
fontWeight: 'bold',
},
});
You can use any of the below two methods to run the app
Method 1: Open the terminal and enter the following command to run the app
npx expo start
You can download the Expo Go app from the Apple App Store (For iOS) or Google Play Store (For Android) to run the app.
Method 2: You can use emulator or connect computer to your device using USB and run the below command
npx react-native run-android
npx react-native run-ios
Output:
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read