-1

I want to play 2 file in reactjs use ReactPlayer , file 1 is video music include audio human voice , file 2 is music only but the human voice has been deleted.

The problem when I run the code below is file 1 may start sooner than file 2 or vice versa , my question is can I play 2 file together , so when file 1 loading or render , file 2 will do same as file 1

This the code

import React, { useState } from "react";
import ReactPlayer from "react-player";

function App(){
  const [playing, setPlaying] = useState(true);
  const [muted, setMuted] = useState(true);

  function handlePlayPause() {
    setPlaying(!playing);
  }

  function handleMuted() {
    setMuted(!muted);
  }

  return(
  <div>
     //play video music "I can fly include the music with human vocal"
     <ReactPlayer
        playing={playing}
        url={"I can Fly.mp4"}
        muted={muted}
      />

      //play music only "I can fly (the file no human vocal)"
      <ReactPlayer
        playing={playing}
        url={"I can fly(no vocal).mp3"}
        muted={!muted}
        hidden
      />
      <button onClick={() => handlePlayPause()}>
        {playing ? "pause" : "play"}
      </button>
      <button onClick={() => handleMuted()}>
        {muted ? "vocal" : "no vocal"}
      </button>
  </div>
)}

export default App;

Hope you guys understand what I'm asking , sorry for my bad English :D

1 Answers1

1

I guess the issue is from a video needs time to get ready before playing. Each video has a different its own time which means each video would have a different time to start playing.

As a result of that, we have to wait until all videos ready before playing them all at once. Luckily, react-player has offered a onReady callback telling that video is ready to play. Here is the general idea for you:

import React from "react";
import ReactPlayer from "react-player";

// Assuming to have 2 videos
const links = [
  "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",
  "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"
];

export default function App() {
  // Count number of videos ready to play
  const [readyCount, setReadyCount] = React.useState(0);
  const [playing, setPlaying] = React.useState(false);

  // Just keep counting as a video ready
  const onReady = () => {
    setReadyCount(readyCount + 1);
  };

  React.useEffect(() => {
    // All videos ready to play, get them played
    if (readyCount === links.length) {
      setPlaying(true);
    }
  }, [readyCount]);

  return (
    <div className="App">
      {links.map((url) => (
        <ReactPlayer key={url} playing={playing} onReady={onReady} url={url} />
      ))}
    </div>
  );
}

I also have created a codesandbox for you: https://codesandbox.io/s/kind-bardeen-59t8f?file=/src/App.js

tmhao2005
  • 14,776
  • 2
  • 37
  • 44