ReactPlayer使两个文件同时播放



我想在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

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

因此,我们必须等到所有视频都准备好后才能同时播放。幸运的是,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

最新更新