0

我尝试在 reactjs 中制作视频播放器

这是我的代码

import "./App.css";
import React, { Component, useState } from "react";
import ReactPlayer from "react-player";\

function App() {
  const [myvideo, setMyvideo] = useState("");
  const arrayqueue = [
    {
      singer: "The Valley",
      videoname: "video/video_test.mp4",
    },
    {
      singer: "My Friend",
      videoname: "video/video_test2.mp4",
    },
    {
      singer: "Say wow",
      videoname: "video/video_test3.mp4",
    },
  ];
  return (
    <div>
      <ReactPlayer url={myvideo} controls={true} />
      <div className="queue-size" id="style-1">
        {arrayqueue.map((item, index) => {
          return (
            <div
              className="row-queue"
              key={index}
              onClick={() => setMyvideo(item.videoname)}
            >
              <div className="column-queue">{item.singer}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

export default App;

我成功在队列中进行 onclick 并将视频设置为 ReactPlayer,我的问题是如何让 ReactPlayer 自动播放队列中的下一个,所以 ReactPlayer 有 2 个选项,如果我不点击队列,视频将从排队,谢谢:)

4

1 回答 1

1

ReactPlayer有一个名为onEnded更多信息here)的道具,可用于在当前媒体播放完毕时触发回调函数。

您可以跟踪当前正在播放的视频的索引,并设置回调以循环播放您的视频数组。

我更新了您的代码并在我更改的行中添加了注释,因此您可以看到一个示例:

import "./App.css";
import React, { Component, useState } from "react";
import ReactPlayer from "react-player";\

function App() {
  const [myvideo, setMyvideo] = useState("");

  // New state to save index of currently playing video
  const [myvideoIndex, setMyvideoIndex] = useState(0);

  const arrayqueue = [
    {
      singer: "The Valley",
      videoname: "video/video_test.mp4",
    },
    {
      singer: "My Friend",
      videoname: "video/video_test2.mp4",
    },
    {
      singer: "Say wow",
      videoname: "video/video_test3.mp4",
    },
  ];

  // Callback function that plays next video (or goes back to first video)
  const playNext = () => {
    const nextIndex = myvideoIndex + 1
    if (nextIndex >= arrayqueue.length) {
      setMyvideo(arrayqueue[0])
      setMyvideoIndex(0)
    } else {
      setMyvideo(arrayqueue[nextIndex])
      setMyvideoIndex(nextIndex)
    }
  }

  // When click, set the video and the current index
  const handleClick = (item, index) => {
    setMyvideo(item.videoname)
    setMyvideoIndex(index)
  }

  return (
    <div>
      <ReactPlayer url={myvideo} controls={true} onEnded={playNext} />
      <div className="queue-size" id="style-1">
        {arrayqueue.map((item, index) => {
          return (
            <div
              className="row-queue"
              key={index}
              onClick={() => handleClick(item, index)}
            >
              <div className="column-queue">{item.singer}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

export default App;
于 2020-11-17T03:42:04.343 回答