如何在 React 中在特定时间戳开始播放视频?

moe*_*ous 3 javascript reactjs react-player

这是我的组件,我想从某个时间(例如 00:07:12,600)自动播放它,而不是从头开始。

import style from './Hero.module.css';
import Image from 'next/image';
import ReactPlayer from 'react-player';
import { useState } from 'react';

export default function Index() {
  const [isPlaying, setIsPlaying] = useState(true);

  return (
    <div className={style.hero_container}>
      {/* <Image src="/images/hero/hero1.jpg" alt="Logo" height={400} width={700} /> */}

      <ReactPlayer
        url="/videos/Dexter.S01E03.1080p.5.1Ch.BluRay.ReEnc-DeeJayAhmed.mkv"
        playing={isPlaying}
        width="100%"
        height="100%"
        controls={true}
      />
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

Gab*_*oli 8

onReady将事件与方法一起使用seekTo

像这样的东西

const playerRef = React.useRef();

const onReady = React.useCallback(() => {
  const timeToStart = (7 * 60) + 12.6;
  playerRef.current.seekTo(timeToStart, 'seconds');
}, [playerRef.current]);

<ReactPlayer
   ref={playerRef}
   url="/videos/Dexter.S01E03.1080p.5.1Ch.BluRay.ReEnc-DeeJayAhmed.mkv"
   playing={isPlaying}
   width="100%"
   height="100%"
   controls={true}
   onReady={onReady}
/>
Run Code Online (Sandbox Code Playgroud)

更新

看起来onReady在每次搜索事件后都会触发,所以我们需要一些额外的逻辑。

  const [isPlaying, setIsPlaying] = React.useState(true);
  const [isReady, setIsReady] = React.useState(false);
  const playerRef = React.useRef();

  const onReady = React.useCallback(() => {
    if (!isReady) {
      const timeToStart = (7 * 60) + 12.6;
      playerRef.current.seekTo(timeToStart, "seconds");
      setIsReady(true);
    }
  }, [isReady]);
Run Code Online (Sandbox Code Playgroud)