How to Play/Pause video or Audio in ReactJS ?
Last Updated :
07 Aug, 2024
Adding multimedia elements, such as videos and audios, to your ReactJS applications can enhance the overall user experience. One common requirement is to provide controls for playing and pausing these media files. In this article, we'll explore how to implement play/pause functionality for videos and audios in ReactJS.
In this article, we will discuss how to turn on/turn off video or audio. We will understand how we can turn on or turn off our video/audio using the toggle button
For better understanding, we will keep the implementation simple.
Creating and Setting up Environment:
Step 1: Create a React app using the following command
npx create-react-app myapp
Step 2: After creating React app move to our project directory using the following command
cd myapp
inside the src folder, you will find the App.js file, we will modify this component.
Project Structure: It will look like the following:

Example: The component is App.js, It has a video element where your video will appear. At the bottom left, there is two toggle button, by which you can toggle your video/audio.
App.js:
JavaScript
import { useEffect, useState, useRef } from "react";
export default function App() {
const [mystream, setmystream] = useState(null);
const [videoswitch, setvideo] = useState(true);
const [audioswitch, setaudio] = useState(true);
const myvideo = useRef(null);
useEffect(() => {
navigator.mediaDevices
.getUserMedia({ video: true, audio: true })
.then((stream) => {
myvideo.current.srcObject = stream;
myvideo.current.autoplay = true;
myvideo.current.muted = false;
setmystream(stream);
});
}, []);
const handleVideo = () => {
if (videoswitch) {
setvideo(false);
mystream.getTracks().forEach(function (track) {
if (track.readyState === "live" &&
track.kind === "video") {
track.enabled = false;
}
});
} else {
setvideo(true);
mystream.getTracks().forEach(function (track) {
if (track.readyState === "live" &&
track.kind === "video") {
track.enabled = true;
}
});
}
};
const handleAudio = () => {
if (audioswitch) {
setaudio(false);
mystream.getTracks().forEach(function (track) {
if (track.readyState === "live" &&
track.kind === "audio") {
track.enabled = false;
}
});
} else {
setaudio(true);
mystream.getTracks().forEach(function (track) {
if (track.readyState === "live" &&
track.kind === "audio") {
track.enabled = true;
}
});
}
};
return (
<div>
<button onClick={handleVideo}>
{videoswitch ? "Turn off video" :
"Turn on video"}
</button>
<button onClick={handleAudio}>
{audioswitch ? "Turn off audio" :
"Turn on audio"}
</button>
<video ref={myvideo} style={{
width: "500px", height: "500px" }}></video>
</div>
);
}
The state used in this component:
- mystream: This state will hold the user media streams.
- videoswitch: This will hold the current status of the video toggle button.
- audioswitch: This will hold the current status of the audio toggle button.
We have used the useRef hook to access the video element and set its srcObject property:
const myvideo = useRef(null);
Now get the user media when the component mounts for the first time using react hook useEffect and set srcObject property of the video element. We have created two onClick event listeners for the buttons so that we can toggle between on/off.
If video or audio is already off we will turn it on using
track.enabled=true
Note: If you want to stop the streaming you can use the track.stop()
Start the Application: Now start the development server using the following command
npm start
Output:
Similar Reads
How to toggle play/pause in ReactJS with audio ?
In this article, we will learn to create a play/pause button for an audio file using ReactJS. Prerequisites:NodeJS or NPMReact JSApproach: Take the reference of the audio file in ReactJS Using Audio Class Set the default state of the song as not playing.Make a function to handle the Play/Pause of th
2 min read
How to Play/Pause video or Audio in camera application in ReactJS ?
In this article, we'll construct a basic Respond application that permits clients to control their video and sound transfers with on/off buttons. We'll utilize symbols to address the video and sound controls for a more easy-to-use interface. This can be valuable for applications like video conferenc
4 min read
How to create Video Player in ReactJS ?
We are going to learn how we can create a Video Player in React JS. A video player is a kind of media player for playing back digital video data. React is a free and open-source front-end JavaScript library for building user interfaces or UI components.Prerequisite:React JSPhases of JavaScript Event
2 min read
How to add Video Player in Next.js ?
Adding a video player in a Next.js application enhances the user experience by enabling video playback. The react-player library simplifies integrating various video sources such as YouTube, Vimeo, and local files. In this article, we are going to learn how we can add Video Player in NextJS. Approac
2 min read
How To Use Modal Component In ReactJS?
Modals are a popular UI component used to display content in a pop-up window like alerts, forms, or additional information. In ReactJS, there are multiple ways to implement a modal. In this article, we will discuss two common approaches: using reusable functional components and using the Material-UI
4 min read
How to use Popper Component in ReactJS ?
A Popper is used to show the part of the content on top of another. It's an alternative feature for react-popper. Material UI for React has this component available for us, and it is simple and very easy to integrate. For perfect positioning, it uses 3rd party library which is Popper.js.Prerequisite
3 min read
How to use Popover Component in ReactJS ?
A Popover is a graphical control which is a container-type element that hovers over the parent window, and it makes sure that all other interaction is blocked until it is selected. Material UI for React has this component available for us, and it is very easy to integrate.PrerequisitesA basic unders
2 min read
How to add Youtube Videos in Next.js ?
In this article, we are going to learn how we can add Youtube Video in NextJs. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components condit
2 min read
How to Perform Debouncing in ReactJS ?
Debouncing in react is used to limit the frequent executions. It is implemented using the lodash debounce method.Debouncing in ReactDebouncing in React is a technique used to limit the execution rate. It prevents excessive function calls for frequent events, like changing the input, and helps improv
3 min read
How to crop images in ReactJS ?
Image cropping is a common requirement in web applications, especially when dealing with user-generated content, photo editing, or image manipulation. ReactJS, being a popular JavaScript library for building user interfaces, provides various techniques and libraries that can be used to implement ima
3 min read