Open In App

How to Play/Pause video or Audio in camera application in ReactJS ?

Last Updated : 10 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 conferencing, where clients need the adaptability to turn their video or sound on and off.

Prerequisites:

Approach to create Camera Appliaction:

  • In the code, we make a React functional component App. We utilize the useState hook to deal with the condition of video and sound controls. The useEffect hook is utilized to demand admittance to the client’s webcam and amplifier and set up the underlying condition of the application.
  • Use the useState hook to manage the state of the user video and audio controls.
  • Initialize states for mystream, videoswitch, and audioswitch.
  • The handleVideo and handleAudio capabilities are answerable for flipping video and sound controls on and off. We use symbols from the respond symbols library to make visual portrayals of these controls.
  • The title trait on the buttons gives tooltip text, which is shown when the client drifts over the buttons.

Steps to create React Application:

Step 1: Create a React app using the following command

npx  create-react-app myapp

Step 2: After creating the React app move to our project directory using the following command

cd myapp

Step 3: Install the react-icons npm package

npm install react-icons

Step 4: Inside the src folder, you will find the App.js file, we will modify this component.

The updated dependencies in package.json file will look like:

"dependencies": {
"@fortawesome/react-fontawesome": "^0.2.0",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"bootstrap": "^5.3.2",
"font-awesome": "^4.7.0",
"react": "^18.2.0",
"react-icons": "^4.11.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Project Structure:

reactProjstructure

Project Structure

Example: Now, let’s build the app. Open the src/App.js file and replace its content with the following code

Javascript




// App.js
 
import {
    useEffect, useState,
    useRef
} from "react";
import {
    FaVideo, FaMicrophone,
    FaVideoSlash, FaMicrophoneSlash
} from 'react-icons/fa';
 
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>
 
            <div style={{
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
            }}>
                <img src=
                    "https://media.geeksforgeeks.org/gfg-gg-logo.svg" />
            </div>
 
            <div
                style={{
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    height: "400px",
                    marginTop: "10px"
                }}
            >
                <video ref={myvideo}
                    style={{
                        width: "500px", height: "400px",
                        transform: "scaleX(-1)"
                    }}>
                </video>
            </div>
            <div style={{
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                marginTop: "10px",
            }}>
                <button
                    onClick={handleVideo}
                    style={{
                        width: "3rem",
                        height: "3rem",
                        borderRadius: "50%",
                        border: "none",
                        backgroundColor: "grey",
                        color: "white"
                    }}
                    title=
                    {videoswitch ?
                        "Turn off video" :
                        "Turn on video"}
                >
                    {videoswitch ? (
                        <FaVideo style={{ fontSize: '1.3rem' }} />
                    ) : (
                        <FaVideoSlash style={{ fontSize: '1.3rem' }} />
                    )}
                </button>
                <button
                    onClick={handleAudio}
                    style={{
                        marginLeft: "10px",
                        width: "3rem",
                        height: "3rem",
                        borderRadius: "50%",
                        border: "none",
                        backgroundColor: "grey",
                        color: "white"
                    }}
                    title=
                    {audioswitch ?
                        "Turn off audio" :
                        "Turn on audio"}
                >
                    {audioswitch ? (
                        <FaMicrophone
                            style={{ fontSize: '1.3rem' }} />
                    ) : (
                        <FaMicrophoneSlash
                            style={{ fontSize: '1.3rem' }} />
                    )}
                </button>
            </div>
        </div>
    );
}


Steps to run the application:Start the development server using the following command:

 npm start

Output: The following output will be displayed on browser.

WebCamGIF

Output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads