Fork me on GitHub

一款开源免费跨浏览器的视频播放器--videojs使用介绍

       最近项目中的视频功能,需要做到浏览器全兼容,所以之前用html5实现的视频功能就需要进行改造了。在网上翻了个遍,试来试去,在所有的视频播放器中,就数它最实际了。首先我们来看看它的优点:

     1.它是开源免费的,你可以在github很容易的获取它的最新代码。

     2.使用它非常的容易,只要花几秒钟就可以架起一个视频播放页面。

     3.它几乎兼容所有的浏览器,并且优先使用html5,在不支持的浏览器中,会自动使用flash进行播放。

     4. 界面可以定制,纯javascript和css打造。说明文档也非常的详细。

下面是官网提供的一个简单的使用方法:

<!DOCTYPE HTML>
<html>
<head>
  <title>Video.js Test Suite</title>
<link href="//vjs.zencdn.net/4.10/video-js.css" rel="stylesheet">
<script src="//vjs.zencdn.net/4.10/video.js"></script>
 
</head>
<body>
 <video id="example_video_1" class="video-js vjs-default-skin" controls width="640" height="264">
 <source src="http://video-js.zencoder.com/oceans-clip.mp4" type='video/mp4' />
</video> 
</body>
</html>

 这样个例子对于想用它做一个电影网站来说够用了。可是我们的需求往往不会只是这么简单。比如我现在要强制在pc端使用flash播放要怎么设置?

有两种途径:

   先说第一种,通过html的data-setup 属性进行设置。

 

<video id="example_video_1" class="video-js vjs-default-skin vjs-big-play-centered"
  controls preload="auto" width="640" height="264"
  poster="http://video-js.zencoder.com/oceans-clip.png"
  data-setup='{ techOrder: ["flash","html5"]}'>
  ...
</video>

第二种就是使用javascript:

  

  videojs('#example_video_1',{
    techOrder: ["flash","html5"]
  },function() {
  
  })

当然,官方的文档说,在内部会自动检测是否支持html5,在不支持的情况下会自动使用flash播放。 

随着单页应用的流行,很多时候,我们在初始化videojs的时候,页面上是不存在存放video的节点的。这个时候,videojs也替我们想到了,我们只需要置空data-setup的属性就可以了。然后在js中进行如下申明:

  

videojs(document.getElementById('example_video_1'), {}, function() {
  // This is functionally the same as the previous example.
});

也就是说,第一个位置,我们直接传dom节点的引用也是可以的。

这时候我们发现,播放按钮默认是在左上角,官方说这样可以不会遮挡内容的精彩部分,但是如果我们想要放到中间,处理也很简单。在video标签中增加一个vjs-big-play-centered样式就好了

<video id="example_video_1" class="video-js vjs-default-skin vjs-big-play-centered"
  controls preload="auto" width="640" height="264"
  poster="http://video-js.zencoder.com/oceans-clip.png"
  data-setup='{"example_option":true}'>
  ...
</video>

如果我们想要它自动播放,非常容易,加一个autoplay 就可以了,或者data-setup='{"autoplay":true}' ,通过js也是一样的道理。非常简单就不演示了。官方说了,由于html5的标准,不建议写成autoplay="true" 或 controls="true",那是html5之前的版本用的。

默认的控制栏会有许多我用不需要用到的组件,比字幕什么的,为了优化,我们可以定义要显示的组件:

 

var player = videojs("example_video_1", {
    "techOrder": ["flash","html"],
    "autoplay":false,
    controlBar: {
        captionsButton: false,
        chaptersButton : false,
        liveDisplay:false,
        playbackRateMenuButton: false,
        subtitlesButton:false
      }

}, function(){

    this.on('loadeddata',function(){
        console.log(this)
    })

    this.on('ended',function(){
         this.pause();
         this.hide()
    })

});

 

我们优化是针对option,因为有些节点我们不需要创建,默认是创建的,这显然会影响效率,以下是我项目中的一个使用情况:

videojs('example_video_1',{
        techOrder : ["html5","flash"],
        children : {
            bigPlayButton : false,
            textTrackDisplay : false,
            posterImage: false,
            errorDisplay : false,
            controlBar : {
                captionsButton : false,
                chaptersButton: false,
                subtitlesButton:false,
                liveDisplay:false,
                playbackRateMenuButton:false
            }
        }
    },function(){
        console.log(this)
    });

对照一下dom节点,少了一大堆,感觉启动明显快了许多。看着也清爽了。

 

打印this看下:

两者是一至的,共有9个对象,于是生成了9个节点,外部只有3个子元素。默认的控制部分会生成14个,外部9个子元素。优化效果非常明显。

初始化的时候,常用的有如下一些参数:

https://github.com/videojs/video.js/blob/stable/docs/guides/options.md

autoplay

自动播放

<video autoplay ...>
or
{ "autoplay": true }

preload

预加载资源

<video preload ...>
or
{ "preload": "auto" }

poster

视频缩略图

<video poster="myPoster.jpg" ...>
or
{ "poster": "myPoster.jpg" }

loop

自动循环

<video loop ...>
or
{ "loop": "true" }

width

The width attribute sets the display width of the video.

<video width="640" ...>
or
{ "width": 640 }

height

The height attribute sets the display height of the video.

<video height="480" ...>
or
{ "height": 480 }

Component Options

功能组件(例中演示如何移除静音按钮)

var player = videojs('video-id', {
  controlBar: {
    muteToggle: false
  }
});

 videojs 有许多的组件,比如声音,播放按钮,字幕,时间,进度条等等,它们在html中的结构类似于这样子:

Player
    PosterImage
    TextTrackDisplay
    LoadingSpinner
    BigPlayButton
    ControlBar
        PlayToggle
        FullscreenToggle
        CurrentTimeDisplay
        TimeDivider
        DurationDisplay
        RemainingTimeDisplay
        ProgressControl
            SeekBar
              LoadProgressBar
              PlayProgressBar
              SeekHandle
        VolumeControl
            VolumeBar
                VolumeLevel
                VolumeHandle
        MuteToggle

 

通常html5会比flash加载的更快,所以我们通常优先使用html5,同时把我们要进行的操作写在回调里边。比如:

videojs("example_video_1").ready(function(){
  var myPlayer = this;

  // EXAMPLE: Start playing the video.
  myPlayer.play();

});

需要强调的是,如果使用flash优先,那么你在本地调式的时候,要用http的方式访问,否则你什么也看不到。

更多的api调用请看这里https://github.com/videojs/video.js/blob/stable/docs/api/vjs.Player.md

METHODS

autoplay
buffered
bufferedEnd
bufferedPercent
cancelFullScreen deprecated
controls
currentSrc
currentTime
currentType
dispose //清理
duration
ended //结束
error //错误
exitFullscreen //退出全屏
init
isFullScreen deprecated 废弃
isFullscreen
language
load
loop //循环
muted 静音
pause 暂停
paused //检测是否暂停的状态
play
playbackRate
poster //静态图片
preload
remainingTime //余下时间
requestFullScreen deprecated
requestFullscreen
seeking
src
volume
addChild inherited
addClass inherited
buildCSSClass inherited
children inherited
contentEl inherited
createEl inherited
dimensions inherited
el inherited
enableTouchActivity inherited
getChild inherited
getChildById inherited
hasClass inherited
height inherited
hide inherited
id inherited
initChildren inherited
name inherited
off inherited
on inherited
one inherited
options inherited
player inherited
ready inherited
removeChild inherited
removeClass inherited
show inherited
trigger inherited
triggerReady inherited
width inherited

这里我说一下几个常用的方法:清理 dispose,hide() 隐藏,show() 显示,play()播放,pause(), el()获取video元素 ,暂停 几本上就差不多了。

最后要说一下的就是事件。官方提示的事件如下:

EVENTS

durationchange
ended
firstplay
fullscreenchange
loadedalldata
loadeddata
loadedmetadata
loadstart
pause
play
progress
seeked
seeking
timeupdate
volumechange
waiting
resize inherited

我们常用的有play播放,pause暂停,ended结束,error错误, loadeddata数据加载完成

videojs的插件机制,我以在播放器的控制条中添加一个关闭按钮为例,展示如果使用插件实现我们自己想要的功能。

videojs.PowerOff = videojs.Button.extend({
              /* @constructor */
               init: function(player, options){

                 videojs.Button.call(this, player, options);
                 //onClick为默认事件,不需要人为邦定,否则会调两次
                 //this.on('click', this.onClick);
               }
             });

            /* This function is called when X button is clicked */
            videojs.PowerOff.prototype.onClick = function() {
                console.log('ddd')
//这里添加做你想要干的事情 };
/* Create X button */ var createPowerOffButton = function() { var props = { className: 'vjs-off-button vjs-control', innerHTML: '<div class="vjs-control-content">X</div>', role: 'button', 'aria-live': 'polite', tabIndex: 0 }; return videojs.Component.prototype.createEl(null, props); }; /* Add X button to the control bar */ var X; videojs.plugin('PowerOff', function() { var options = { 'el' : createPowerOffButton() }; X = new videojs.PowerOff(this, options); this.controlBar.el().appendChild(X.el()); });

调用的时候,参数要加上插件的名称:

var player = videojs("example_video_1", {
      plugins : { PowerOff : {} }
}, function(){
    
});

看到我们添加的“X” 了没有?什么,你的X是在中间?忘了告诉你,这个地方的样式要自己加上,我的是这样的

.vjs-default-skin .vjs-control.vjs-off-button {
         display: block;
         font-size: 1.5em;
         line-height: 2;
         position: relative;
         top: 0;
         float:right;
         left: 10px;
         height: 100%;
         text-align: center;
         cursor: pointer;
         }

是不是相当的nice呀。

在实践中,我发现flash模式和html5模式还是有一些不一致的地方。

比如在flash模式中,在播放器暂停或隐藏之后,调用paused()方法报错:VIDEOJS: Video.js: paused unavailable on Flash playback technology element.

调用hide()之后,调用show()方法,在flash模式中,会自动调用播放,而且是重新开始,而html5模式则不会。对于这一点,解决的办法是在option中指定autoplay:false,这样两者行为就一致了。

使用videojs我发现有几个地方是要注意的:

1:在iframe加载的页面中,全屏按钮是无效的。当然后来证实不是videojs的问题,是iframe要加allowfullscreen 属性才行。

2:在flash模式下有太多的问题,比哪重复调用pause()会报错,在hide()之后调用paused()会报错。

3:在flash模式下不要试图使用audio去播放音频,虽然有插件可以支持,但是问题很多。html5模式下本人没有测试。

videojs 在flash模式下,以下情况有冲突:
1. video 在播中调用hide()会导致内部错误,如果先调用了pause()和hide(),再调用pause()同样会导致内部错误。类似的情况还有调用dispose()
2. 在video是hide的情况下,去调用paused()会产生内部错误
3. 在hide的状态下,调用show()再调用play会产生内部错误
4. 在文件不存在的情况下,如果不调用dispose会产生内部错误。

综上所述,对于单页应用,videojs在隐藏时,内部的状态就存在丢失的情况,会导致一系列的问题。解决的办法就是播一次就创建一次。关闭就清理。经测试,这种模式就再也不会有错误了

 仅管如此,作为一个开源免费的产品,已经是相当不错了。

videojs已更新,请移动更新之后的文章

posted on 2014-11-25 15:49  bjtqti  阅读(69850)  评论(11编辑  收藏  举报