-1

我想播放正在reactjs使用的 2 个文件ReactPlayer,文件 1 是视频音乐,包括音频人声,文件 2 只是音乐,但人声已被删除。

当我运行下面的代码时的问题是文件 1 可能比文件 2 更早开始,反之亦然,我的问题是我可以一起播放 2 个文件,所以当文件 1 加载或渲染时,文件 2 将与文件 1 执行相同的操作

这是代码

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;

希望你们明白我在问什么,对不起我的英语不好:D

4

1 回答 1

1

我想问题出在视频需要时间在播放前做好准备。每个视频都有不同的时间,这意味着每个视频都有不同的开始播放时间。

因此,我们必须等到所有视频都准备好后再一次播放。幸运的是,react-player提供了一个onReady回调,告知视频已准备好播放。以下是您的总体思路:

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>
  );
}

我还为您创建了一个代码框:https ://codesandbox.io/s/kind-bardeen-59t8f?file=/src/App.js

于 2020-11-18T04:38:31.367 回答