Open In App

How to Play/Pause video or Audio in ReactJS ?

Last Updated : 05 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads