javascript 如何在React中以特定时间戳启动录像?

hgc7kmma  于 2023-01-07  发布在  Java
关注(0)|答案(2)|浏览(137)

这是我的组件,我想从某个时间(如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>
  );
}
koaltpgm

koaltpgm1#

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}
/>
    • 更新**

看起来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]);
zc0qhyus

zc0qhyus2#

您可以使用seekTo函数在特定时间启动视频。

工作演示

class Player extends React.Component {
  render () {
    return (
        <div className='player-wrapper'>
        <ReactPlayer
          ref={p => { this.p = p }}
          url='//s3.envoy.rocks/bothrs/goud-design-sprint/goud/LhgEcS_GOUD+PROTOTYPE+SHOWCASE.mp4'
          className='react-player'
          playing
          controls
          width='100%'
          height='100%'
        />
        <button onClick={() => this.p.seekTo(0.9999999)}>Seek to end</button>
        <button onClick={() => this.p.seekTo(0.999)}>Seek to end (works in Safari)</button>
        <button onClick={() => {
    console.log(this.p.getDuration());this.p.seekTo(this.p.getDuration())}}>Seek to end (with getDuration())</button>
        <button onClick={() => this.p.seekTo(12.7)}>Seek to 12.7</button>
        <button onClick={() => this.p.seekTo(42.65)}>Seek to 42.65</button>
      </div>
    )
  }
}

ReactDOM.render(
  <Player />,
  document.getElementById('container')
);

更新如果你想在特定时间开始视频,那么我认为useEffect与空依赖关系将是最好的方法。

useEffect(() => {
   this.p.seekTo(12.7)
}, [])

相关问题