【问题标题】:ReactPlayer make 2 file play in same timeReactPlayer同时播放2个文件
【发布时间】:2021-03-01 07:47:34
【问题描述】:

我想在reactjs使用ReactPlayer播放2个文件,文件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

【问题讨论】:

    标签: javascript reactjs react-player


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2021-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多