useVideo

创建 <video> 元素,追踪其状态并暴露播放控件。

用法

  1. import {useVideo} from 'react-use';
  2. const Demo = () => {
  3. const [video, state, controls, ref] = useVideo(
  4. <video src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" autoPlay />
  5. );
  6. return (
  7. <div>
  8. {video}
  9. <pre>{JSON.stringify(state, null, 2)}</pre>
  10. <button onClick={controls.pause}>Pause</button>
  11. <button onClick={controls.play}>Play</button>
  12. <br/>
  13. <button onClick={controls.mute}>Mute</button>
  14. <button onClick={controls.unmute}>Un-mute</button>
  15. <br/>
  16. <button onClick={() => controls.volume(.1)}>Volume: 10%</button>
  17. <button onClick={() => controls.volume(.5)}>Volume: 50%</button>
  18. <button onClick={() => controls.volume(1)}>Volume: 100%</button>
  19. <br/>
  20. <button onClick={() => controls.seek(state.time - 5)}>-5 sec</button>
  21. <button onClick={() => controls.seek(state.time + 5)}>+5 sec</button>
  22. </div>
  23. );
  24. };

参考

  1. const [video, state, controls, ref] = useVideo(props);
  2. const [video, state, controls, ref] = useVideo(<video {...props}/>);

video 是 React 的 <video> 元素,你必须在渲染树中的某处插入,例如:

  1. <div>{video}</div>

state 追踪音频的状态,并具有以下状态:

  1. {
  2. "buffered": [
  3. {
  4. "start": 0,
  5. "end": 425.952625
  6. }
  7. ],
  8. "time": 5.244996,
  9. "duration": 425.952625,
  10. "isPlaying": false,
  11. "muted": false,
  12. "volume": 1
  13. }

controls 是一个方法列表集合,运行你控制视频的播放,它有以下接口:

  1. interface AudioControls {
  2. play: () => Promise<void> | void;
  3. pause: () => void;
  4. mute: () => void;
  5. unmute: () => void;
  6. volume: (volume: number) => void;
  7. seek: (time: number) => void;
  8. }

ref 是对 HTML <video> 元素的 React 引用,你可以通过 ref.current 访问该元素,注意它可能是 null

最后,props<video> 接收所有的属性。