1.安装video.js
npm i video.js
2.配置video组件
这里我直接基于官网给的集成React的demo配置的,官网的demo其实已经比较完善
官网链接:https://gitcode.gitcode.host/docs-cn/video.js-docs-cn/docs/guides/react.html
我用的是函数式组件,官方demo如下:
import React from "react";
import videojs from "video.js";
import "video.js/dist/video-js.css";
export const VideoJS = ( props ) => {
const videoRef = React.useRef(null);
const playerRef = React.useRef(null);
const { options, onReady } = props;
React.useEffect(() => {
// make sure Video.js player is only initialized once
if (!playerRef.current) {
const videoElement = videoRef.current;
if (!videoElement) return;
const player = playerRef.current = videojs(videoElement, options, () => {
console.log("player is ready");
onReady && onReady(player);
});
} else {
// you can update player here [update player through props]
// const player = playerRef.current;
// player.autoplay(options.autoplay);
// player.src(options.sources);
}
}, [options, videoRef]);
// Dispose the Video.js player when the functional component unmounts
React.useEffect(() => {
const player = playerRef.current;
return () => {
if (player) {
player.dispose();
playerRef.current = null;
}
};
}, [playerRef]);
return (
<div data-vjs-player>
<video ref={videoRef} className="video-js vjs-big-play-centered" />
</div>
);
}
export default VideoJS;
import React from "react";
import VideoJS from './VideoJS' // point to where the functional component is stored
const App = () => {
const playerRef = React.useRef(null);
const videoJsOptions = { // lookup the options in the docs for more options
autoplay: true,
controls: true,
responsive: true,
fluid: true,
sources: [{
src: '/path/to/video.mp4',
type: 'video/mp4'
}]
}
const handlePlayerReady = (player) => {
playerRef.current = player;
// you can handle player events here
player.on('waiting', () => {
console.log('player is waiting');
});
player.on('dispose', () => {
console.log('player will dispose');
});
};
// const changePlayerOptions = () => {
// // you can update the player through the Video.js player instance
// if (!playerRef.current) {
// return;
// }
// // [update player through instance's api]
// playerRef.current.src([{src: 'http://ex.com/video.mp4', type: 'video/mp4'}]);
// playerRef.current.autoplay(false);
// };
return (
<>
<div>Rest of app here</div>
<VideoJS options={videoJsOptions} onReady={handlePlayerReady} />
<div>Rest of app here</div>
</>
);
}
3.展示总时长和目前播放进度
因为默认是在css中使用display:none将视频总时长和视频目前播放进度隐藏的,所以需要自己在样式文件中再修改一下
.video-js .vjs-duration, .vjs-no-flex .vjs-duration {
display: inline-block!important;
}
.video-js .vjs-current-time, .vjs-no-flex .vjs-current-time {
display: inline-block!important;
}
4.添加监听事件
对handlePlayerReady方法进行修改,添加不同的监听事件。我使用的监听事件如下
const handlePlayerReady = player => {
playerRef.current = player
player.on('loadedmetadata', () => {
// 获取资源长度完成
})
player.on('play', () => {
// 视频开始播放
})
player.on('ended', () => {
// 播放结束
})
player.on('dispose', () => {
// 组件销毁
})
player.on('pause', () => {
// 视频暂停
})
}