1

Here I tried to play audio and video simultaneously, but the page goes blank when I try to run it. Is there a way I can fix this? This is the code

import React from 'react'
import './home.css'
import { useState } from 'react';
import { useEffect } from 'react';
import video1 from './Ankit.mp4';
import Newhome from './Newhome';
import audio from './sound.mp3';
export default function Home() {
    
    const [showVideo, setShowVideo] = useState(true);
    useEffect(
        () => {
            let timer1 = setTimeout(() => setShowVideo(false), 3500);
            return () => {
                // <div>Best viewed on mobile for now</div>
            clearTimeout(timer1);
          };
        },
        []
      );
    return (
        <>
            {showVideo ? <video  muted autoPlay loop className='logo_video2' >
                <source src={video1} type="video/mp4" />
                  <audio controls>
                <source src={audio} type="audio/mpeg" />
            </audio>
            </video> : <Newhome/>}
        </>
    )
}

showVideo is used to play a logo and 3.5 seconds after all content will be displayed.

Ankit
  • 1,359
  • 1
  • 2
  • 15

1 Answers1

2

You have to pass the prop Home to Audio component, as you can see the below, and in Audio component you are giving the wrong audio tag you have to change the Audio to audio.

import React, { useEffect } from "react";
export default function Audio({ src }) {
  useEffect(() => {
const eleId = document.getElementById("audioId");
   if (eleId) {
     eleId.src = src;
     eleId.play();
    }
  }, [src]);

  return (
    <>
      <div>
        <audio id="audioId" autplay controls></audio>
      </div>
    </>
  );
}

Home.jsx

import React from "react";
import "./home.css";
import Audio from "./Audio";
import { useState } from "react";
import { useEffect } from "react";
import video1 from "./Ankit.mp4";
import Newhome from "./Newhome";
import audio from "./sound.mp3";
export default function Home() {
  const [showVideo, setShowVideo] = useState(true);
  useEffect(() => {
    let timer1 = setTimeout(() => setShowVideo(false), 3500);
    return () => {
      // <div>Best viewed on mobile for now</div>
      clearTimeout(timer1);
    };
  }, []);
  return (
    <>
      {showVideo ? (
        <video muted autoPlay loop className="logo_video2">
          <source src={video1} type="video/mp4" />
          <Audio src={audio}></Audio>
        </video>
      ) : (
        <Newhome />
      )}
    </>
  );
}
Ahmad Faraz
  • 1,371
  • 1
  • 4
  • 11