# videojs
# 安装
cnpm install --save video.js flv.js videojs-flvjs-es6
- flv.js支持flv类型文件或者流的播放
当前项目中执行cnpm install --save videojs-contrib-hls,依然可以播放m3u8的视频
# 开发步骤
// wrap the player in a div with a `data-vjs-player` attribute
// so videojs won't create additional wrapper in the DOM
// see https://github.com/videojs/video.js/pull/3856
<div data-vjs-player>
<video ref={node => this.videoNode = node} className="video-js vjs-default-skin video"
autoPlay="autoplay"/>
</div>
// 或者
<div data-vjs-player>
<video id={`video${containerId}`} className="video-js vjs-default-skin video"
autoPlay="autoplay"/>
</div>
2
3
4
5
6
7
8
9
10
11
12
13
播放并切换地址播放
import videojs from 'video.js';
import 'videojs-flvjs-es6';
import 'video.js/dist/video-js.min.css';
// Don't forget to include the Video.js CSS, located at video.js/dist/video-js.css.
/**
* videoJs属性
*/
const videoJsOptions = ({ height = 520 }) => ({
// techOrder: ['html5', 'Flvjs'],For v5 the tech must be added to the tech order.For v6 this is not needed.
flvjs: {
mediaDataSource: {
isLive: true,
cors: true,
withCredentials: false,
},
},
autoplay: true,
controls: true,
height,
});
this.setState({ videoPlayer: videojs(this.videoNode, videoJsOptions({})) });
// 或者
useEffect(() => {
setVideoPlayer(videojs(`video${containerId}`, { ...videoJsOptions({ height: 180 }), width: 290 }))
return () => {
videoPlayer.dispose();
setVideoPlayer(null);
}
}, []);
videoPlayer.reset();
videoPlayer.src({
src: finalUrl,
type: findVideoSrcType(finalUrl),
});
videoPlayer.load();
videoPlayer.play();
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# videojs初始化方式
# 直接在<video>中初始化
<video
id="my-player"
class="video-js"
controls
preload="auto"
poster="//vjs.zencdn.net/v/oceans.png"
width="600"
height="400"
data-setup='{}'>
<source src="//vjs.zencdn.net/v/oceans.mp4" type="video/mp4"></source>
<source src="//vjs.zencdn.net/v/oceans.webm" type="video/webm"></source>
<source src="//vjs.zencdn.net/v/oceans.ogv" type="video/ogg"></source>
<p class="vjs-no-js">
To view this video please enable JavaScript, and consider upgrading to a
web browser that
<a href="https://videojs.com/html5-video-support/" target="_blank">
supports HTML5 video
</a>
</p>
</video>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 在js中初始化
<!-- vjs-big-play-centered可使大的播放按钮居住,vjs-fluid可使视频占满容器 -->
<video id="myVideo" class="video-js vjs-big-play-centered vjs-fluid">
<p class="vjs-no-js">
To view this video please enable JavaScript, and consider upgrading to a
web browser that
<a href="https://videojs.com/html5-video-support/" target="_blank">
supports HTML5 video
</a>
</p>
</video>
<script>
var player = videojs(document.getElementById('myVideo'), {
controls: true, // 是否显示控制条
poster: 'xxx', // 视频封面图地址
preload: 'auto',
autoplay: false,
fluid: true, // 自适应宽高
language: 'zh-CN', // 设置语言
muted: false, // 是否静音
inactivityTimeout: false,
controlBar: { // 设置控制条组件
/* 设置控制条里面组件的相关属性及显示与否
'currentTimeDisplay':true,
'timeDivider':true,
'durationDisplay':true,
'remainingTimeDisplay':false,
volumePanel: {
inline: false,
}
*/
/* 使用children的形式可以控制每一个控件的位置,以及显示与否 */
children: [
{name: 'playToggle'}, // 播放按钮
{name: 'currentTimeDisplay'}, // 当前已播放时间
{name: 'progressControl'}, // 播放进度条
{name: 'durationDisplay'}, // 总时间
{ // 倍数播放
name: 'playbackRateMenuButton',
'playbackRates': [0.5, 1, 1.5, 2, 2.5]
},
{
name: 'volumePanel', // 音量控制
inline: false, // 不使用水平方式
},
{name: 'FullscreenToggle'} // 全屏
]
},
sources:[ // 视频源
{
src: '//vjs.zencdn.net/v/oceans.mp4',
type: 'video/mp4',
poster: '//vjs.zencdn.net/v/oceans.png'
}
]
}, function (){
console.log('视频可以播放了',this);
});
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Using a React Component as a Video JS Component
/**
* EpisodeList.js
*
* This is just a plain ol' React component.
* the vjsComponent methods, player methods etc. are available via
* the vjsComponent prop (`this.props.vjsComponent`)
*/
import React, { Component, PropTypes } from 'react';
class EpisodeList extends Component {
render() {
return (
<div>
<h1>{this.props.body}</h1>
</div>
);
}
}
/**
* vjsEpisodeList.js
*
* Here is where we register a Video JS Component and
* mount the React component to it when the player is ready.
*/
import EpisodeList from './EpisodeList';
import ReactDOM from 'react-dom';
import videojs from 'video.js';
const vjsComponent = videojs.getComponent('Component');
class vjsEpisodeList extends vjsComponent {
constructor(player, options) {
super(player, options);
/* Bind the current class context to the mount method */
this.mount = this.mount.bind(this);
/* When player is ready, call method to mount React component */
player.ready(() => {
this.mount();
});
/* Remove React root when component is destroyed */
this.on("dispose", () => {
ReactDOM.unmountComponentAtNode(this.el())
});
}
/**
* We will render out the React EpisodeList component into the DOM element
* generated automatically by the VideoJS createEl() method.
*
* We fetch that generated element using `this.el()`, a method provided by the
* vjsComponent class that this class is extending.
*/
mount() {
ReactDOM.render(<EpisodeList vjsComponent={this} body="Episodes" />, this.el() );
}
}
/**
* Make sure to register the vjsComponent so Video JS knows it exists
*/
vjsComponent.registerComponent('vjsEpisodeList', vjsEpisodeList);
export default vjsEpisodeList;
/**
* VideoPlayer.js
* Check the above example for how to integrate the rest of this class.
*/
// ...
componentDidMount() {
// instantiate Video.js
this.player = videojs(this.videoNode, this.props, function onPlayerReady() {
console.log('onPlayerReady', this)
});
/**
* Fetch the controlBar component and add the new vjsEpisodeList component as a child
* You can pass options here if desired in the second object.
*/
this.player.getChild('controlBar').addChild('vjsEpisodeList', {});
}
// ...
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# controlBar组件说明
playToggle, //播放暂停按钮
volumeMenuButton,//音量控制
currentTimeDisplay,//当前播放时间
timeDivider, // '/' 分隔符
durationDisplay, //总时间
progressControl, //点播流时,播放进度条,seek控制
liveDisplay, //直播流时,显示LIVE
remainingTimeDisplay, //当前播放时间
playbackRateMenuButton, //播放速率,当前只有html5模式下才支持设置播放速率
fullscreenToggle //全屏控制
2
3
4
5
6
7
8
9
10
currentTimeDisplay,timeDivider,durationDisplay是相对于remainingTimeDisplay的另一套组件,后者只显示当前播放时间,前者还显示总时间。若要显示成前者这种模式,即 '当前时间/总时间',可以在初始化播放器选项中配置:
# videojs样式修改
.video-js{ /* 给.video-js设置字体大小以统一各浏览器样式表现,因为video.js采用的是em单位 */
font-size: 14px;
}
.video-js button{
outline: none;
}
.video-js.vjs-fluid,
.video-js.vjs-16-9,
.video-js.vjs-4-3{ /* 视频占满容器高度 */
height: 100%;
background-color: #161616;
}
.vjs-poster{
background-color: #161616;
}
.video-js .vjs-big-play-button{ /* 中间大的播放按钮 */
font-size: 2.5em;
line-height: 2.3em;
height: 2.5em;
width: 2.5em;
-webkit-border-radius: 2.5em;
-moz-border-radius: 2.5em;
border-radius: 2.5em;
background-color: rgba(115,133,159,.5);
border-width: 0.12em;
margin-top: -1.25em;
margin-left: -1.75em;
}
.video-js.vjs-paused .vjs-big-play-button{ /* 视频暂停时显示播放按钮 */
display: block;
}
.video-js.vjs-error .vjs-big-play-button{ /* 视频加载出错时隐藏播放按钮 */
display: none;
}
.vjs-loading-spinner { /* 加载圆圈 */
font-size: 2.5em;
width: 2em;
height: 2em;
border-radius: 1em;
margin-top: -1em;
margin-left: -1.5em;
}
.video-js .vjs-control-bar{ /* 控制条默认显示 */
display: flex;
}
.video-js .vjs-time-control{display:block;}
.video-js .vjs-remaining-time{display: none;}
.vjs-button > .vjs-icon-placeholder:before{ /* 控制条所有图标,图标字体大小最好使用px单位,如果使用em,各浏览器表现可能会不大一样 */
font-size: 22px;
line-height: 1.9;
}
.video-js .vjs-playback-rate .vjs-playback-rate-value{
line-height: 2.4;
font-size: 18px;
}
/* 进度条背景色 */
.video-js .vjs-play-progress{
color: #ffb845;
background-color: #ffb845;
}
.video-js .vjs-progress-control .vjs-mouse-display{
background-color: #ffb845;
}
.vjs-mouse-display .vjs-time-tooltip{
padding-bottom: 6px;
background-color: #ffb845;
}
.video-js .vjs-play-progress .vjs-time-tooltip{
display: none!important;
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# videojs动态切换视频源
<script>
var data = {
src: 'xxx.mp4',
type: 'video/mp4'
};
var player = videojs('myVideo', {...});
player.pause();
player.reset(); //重置 video,已经开始播放的播放器需重置播放器
player.src(data);
player.load(data);
// 动态切换poster
player.posterImage.setSrc('xxx.jpg');
player.play();
// 销毁videojs,此方法会清除掉<video>组件
//player.dispose();
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# videojs自定义播放按钮
registerControlComponent() {
const self = this;
const Component = videojs.getComponent("Component");
const Button = videojs.getComponent("Button");
class ControlBtn extends Button {
constructor(player, options = {}) {
super(player, options);
this.on(player, "play", this.handlePlay);
this.on(player, "pause", this.handlePaused);
this.on(this.el(), ["click", "tap"], this.handleControlClick);
}
buildCSSClass() {
return "vjs-control-btn vjs-paused";
// return `vjs-play-control ${super.buildCSSClass()}`
}
handlePlay(e) {
// this.removeClass('vjs-ended')
this.removeClass("vjs-paused");
this.addClass("vjs-playing");
this.controlText("Pause");
// self.$emit('play')
}
handlePaused(e) {
this.removeClass("vjs-playing");
this.addClass("vjs-paused");
this.controlText("Play");
// self.$emit('play')
}
handleControlClick(e) {
// console.log(this)
this.player_.paused() ? this.player_.play() : this.player_.pause();
// self.$emit('play')
}
getPlayStatus() {
return "status";
}
}
Component.registerComponent("ControlBtn", ControlBtn);
},
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# videojs销毁dispose
dispose()从播放器中删除所有事件侦听器。删除播放器的DOM元素,所以再次初始化的时候需要我们重新创建标签
<div class="video-box">
<video id="video" class="video-js vjs-default-skin vjs-big-play-centered" controls preload="none"></video>
</div>
2
3
if (this.myPlayer) {
this.myPlayer.dispose();
$(".video-box").html('<video id="video" class="video-js vjs-default-skin" controls width="640" height="264"></video>');
}
this.$nextTick(() => {
this.myPlayer = videojs('video', {
//确定播放器是否具有用户可以与之交互的控件。没有控件,启动视频播放的唯一方法是使用autoplay属性或通过Player API。
controls: true,
//自动播放属性,muted:静音播放
muted: true,
autoplay: true,
//建议浏览器是否应在<video>加载元素后立即开始下载视频数据。
preload: "auto",
//设置视频播放器的显示宽度(以像素为单位)
width: "960px",
//设置视频播放器的显示高度(以像素为单位)
height: "522px",
// url
// poster: 'https://static.shuxuejia.com/img/video_image.png',
sources: [{
src: item.livingPath
}],
playbackRates: [0.5, 1, 1.5, 2] //倍速播放
}, function onPlayerReady() {
videojs.log('Your player is ready!'); // 比如: 播放量+1请求
this.on('ended', function() {
videojs.log('Awww...over so soon?!');
});
});
});
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# vue中使用videojs
<template>
<video playsinline id="myPlayer" class="video-js vjs-default-skin" width="100%" controls preload="auto" data-setup='{ "aspectRatio":"16:9" }'></video>
</template>
<script>
window.videojs = require('video.js');
export default {
data(){
return{
player: '',
url: 'https://someurl.com',
volume: 1
};
},
methods: {
playerInitialize(){
this.player = videojs('myPlayer');
},
playerDispose(){
this.player.dispose();
},
playerPlay(){
this.player.play();
},
playerPause(){
this.player.pause();
},
playerSetSrc(url){
this.player.src(url);
},
playerSetVolume(float){
this.player.volume(float);
},
playerSetPoster(url){
this.player.poster(url);
},
playerSetTime(time){
this.player.currentTime(time);
},
playerEventEnded(){
console.log('ended');
},
playerEventVolume(){
this.volume = this.player.volume();
},
playerEventError(){
console.log( this.playerGetError() )
},
playerGetPaused(){
return this.player.paused();
},
playerGetTime(){
return this.player.currentTime();
},
playerGetError(){
return this.player.error().message;
},
playerSetupEvents(){
this.player.on('ended', function(){ var a = window.playerEvents.playerEventEnded(); });
this.player.on('volumechange', function(){ window.playerEvents.playerEventVolume(); });
this.player.on('error', function(){ window.playerEvents.playerEventError(); });
},
},
mounted(){
window.playerEvents = this;
this.playerInitialize();
this.playerSetSrc(this.url);
this.playerSetupEvents();
},
beforeDestroy() {
this.playerDispose();
}
}
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# videojs错误收集
# VIDEOJS: WARN: Player "player3" is already initialised. Options will not be applied
页面加载完毕之后,点击请求,页面重新渲染,展示新的数据,如果再次请求和初始化相同的数据,就会出现这个错误提示,其实就是告诉你ID为player3的视频加载容器已经加载过了,不需要重新加载,这样的话,再次加载不能播放视频。解决的方法是,在页面重新渲染的时候,销毁video.js-dispose()
不能重复调用video作用于同一个video,否则报错.每次离开页面需调用实例的dispose()方法销毁实例后再创建实例
video.js同一个id只能初始化一次,但是在react中,一个组建被重复渲染是一件很平常的事情,因此在react中的video.js很容易遇到VIDEOJS: WARN: Player “id_video” is already initialised. Options will not be applied.这个报错,解决方案就是在适当的时候调用dispose()方法销毁video.js对象:
当然不一定在destroyed()的时候销毁,在“适当的时候”调用dispose()即可,否则同一个id,video.js无法多次渲染。但是dispose方法会将 video元素删除,因此dispose后需要再手动创建一个video,下面看一个可复用vue中使用区分video id的简单例子:
this.video_hash=Math.random().toString(36).substr(2);//刷新video_hash
//利用dom创建video
let video = document.createElement('video');
video.setAttribute('id', 'video'+this.rdid+this.video_hash);
video.className = 'video-js';
video.setAttribute('ebkit-playsinline', 'true');
video.setAttribute('playsinline', 'true');
video.setAttribute('controls', 'true');
video.setAttribute('preload', 'auto');
video.setAttribute('poster', this.mediaUrl+'?vframe/jpg/offset/1');//后台返回的mp4路径,获取mp4封面
let source = document.createElement('source');
source.setAttribute('type', 'video/mp4');
source.setAttribute('src', this.mediaUrl);//后台返回的mp4路径
video.appendChild(source);
this.$refs.mp4_container.appendChild(video);
let player = Video('video'+this.rdid+this.video_hash, { //初始化视频
width: this.$refs.mp4_container.clientWidth,
});
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# DOMException: "'#1098942864706113536' is not a valid selector"
video.js 在获取页面元素时使用的是querySelector方法,由于querySelector是按css规范来实现的,所以它传入的字符串中第一个字符不能是数字。
# defaultPlaybackRate unavailable on Html5 playback technology
video被dispose,导致再次加载时失败
# video.js播放全屏,播放完恢复的代码
const options = {
controls: true,
poster: detail.cover
}
this.player = videojs('id_video', options, () => {
this.player.src({
src: detail.playurl
})
// 监听播放
this.player.on('play', () => {
const isFullscreen = this.player.isFullscreen() // 检测满屏
if (!isFullscreen) {
this.player.requestFullscreen() // 进入满屏事件
}
})
// 监听结束
this.player.on('ended', () => {
this.player.exitFullScreen() // 退出满屏事件
})
})
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20