自定义 HTML5 视频搜索栏无法作为视频进度

Custom HTML5 video seekbar not working as video progress

我正在使用 react with typescript。我使用 html5 元素范围作为搜索栏。我在搜索栏上创建了两个事件,一个是 onChange,第二个是 onTimeUpdate。搜索栏在我手动拖动时工作正常,但在视频播放时它不会改变。

这是我的代码:

const VideoPlayer = () => {
    const seekbarRef = useRef(null);
    const vRef= useRef(null);

    const updateSeekbar = () => {
        let videoReference = vRef.current;
        let seekbarReference = seekbarRef.current;
        if(seekbarReference && videoReference){
            let seekbarMax: number = seekbarReference.max as unknown as number;
            let seekbarDuration: number = videoReference.duration;
            let seekbarCurrentTime: number = videoReference.currentTime;
            let seekbarValue: number = (seekbarMax / seekbarDuration) * seekbarCurrentTime;
            seekbarReference.value = seekbarValue as unknown as string;
        }
    }

    const updateDuration = () => {
        let videoReference = vRef.current;
        let seekbarReference = seekbarRef.current;
        if(seekbarReference && videoReference){
            let seekbarMax: number = seekbarReference.max as unknown as number;
            let videoDuration: number = videoReference.duration;
            let seekbarValue: number = seekbarReference.value as unknown as number;
            let videoCurrentTime: number = videoDuration * (seekbarValue / seekbarMax);
            videoReference.currentTime = videoCurrentTime;
        }
    }

    return <div>
  <video className='video' ref={vRef} autoPlay muted>
  <source src='https://www.w3schools.com/html/movie.mp4' />
</video>
<input className='seekbar' type='range' min='0' max='100' onChange={updateDuration} onTimeUpdate={updateSeekbar} ref={seekbarRef}></input>
</div>
};

我不使用 React,但你需要这些修复:

  • (1)"timeupdate" 的事件侦听器添加到您的 video 元素。

  • (2) 计算 [video timeline] 滑块的位置为:

    seekbarValue = ( (seekbarCurrentTime / seekbarDuration) * seekbarMax );