video.js在react中实现视频播放(video.js)

该博客介绍了如何在React项目中集成video.js库,实现视频播放。通过安装video.js,设置视频源和配置项,利用useRef和useEffect实现视频组件。同时,展示了如何自定义控制条并展示视频当前进度和总时长。代码示例详细说明了整个过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

github地址:https://github.com/videojs/video.js

MP4视频地址:http://vjs.zencdn.net/v/oceans.mp4(引用[mp4视频资源])

在这里插入图片描述

在这里插入图片描述

react项目中安装video.js

npm install --save-dev video.js

完整代码

import React, { useState, useRef, useEffect } from "react";
import videojs from "video.js";
import "video.js/dist/video-js.css";
import './index.less';


export default function VideoPlay(props) {
  const { } = props;
  const videoRef = useRef(null);
  const playerRef = useRef<any>(null);
  const [option, setOptopm] = useState({});

  const onReadyPlay = (palyer) => {
    videoRef.current = palyer
    palyer.play();
  }

  const init = () => {
    let _option = {
      controls: true,
      autoplay: false,//加载完成是否自动播放
      loop: false,//视频播放结束后,是否循环播放
      notSupportedMessage: '此视频暂无法播放,请稍后再试',
      poster: 'https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF',//视频封面
      controlBar: {
        // timeDivider: true,//是否显示时间控制条,默认为true
        // remainingTimeDisplay: false,//是否显示剩余时间,默认为true
        // fullscreenToggle: true // 全屏按钮
        children: [//自定义
          { name: 'playToggle' }, // 播放按钮
          {
            name: 'volumePanel', // 音量控制
            inline: false, // 不使用水平方式
          },
          { name: 'currentTimeDisplay' }, // 当前已播放时间
          { name: 'durationDisplay' }, // 总时间
          { name: 'progressControl' }, // 播放进度条
          {
            name: 'pictureInPictureToggle'//支持画中画
          },
          {
            name: 'FullscreenToggle'//支持全屏
          }
        ]
      }

    }
    setOptopm(_option);

    if (!playerRef.current) {
      const videoElement = videoRef.current;
      if (!videoElement) return;

      const player = playerRef.current = videojs(videoElement, _option, () => {
      });
      onReadyPlay(player)
    }
  }

  useEffect(() => {
    init();
  }, [])

  return (
    <div className="video_play">
      <video style={{
        width: 600,
        height: 300
      }} ref={videoRef}
        className="video-js vjs-big-play-centered">
        <source src={`http://vjs.zencdn.net/v/oceans.mp4`} type="video/mp4" />
        <source src={`https://live-s3m.mediav.com/nativevideo/2a80d171cc7ef2c764c9a83c06e0e4bc-bit_cloud768.mp4`} type="video/mp4" />
      </video>
    </div>
  )
}

视频当前进度及视频总时长还需要设置样式,默认的display:none;会直接隐藏。

.video-js .vjs-duration, .vjs-no-flex .vjs-duration {
  display: inline-block;
}
.video-js .vjs-current-time, .vjs-no-flex .vjs-current-time {
  display: inline-block;

}
import VideoPlay from '@/components/VideoPlay';


 <VideoPlay />

以上只针对可播放mp4资源

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值