1. 程式人生 > >【轉】一款開源免費跨瀏覽器的視頻播放器--videojs使用介紹

【轉】一款開源免費跨瀏覽器的視頻播放器--videojs使用介紹

med padding 網站 最新代碼 html 但是 videojs let live

特別提示:本人博客部分有參考網絡其他博客,但均是本人親手編寫過並驗證通過。如發現博客有錯誤,請及時提出以免誤導其他人,謝謝!歡迎轉載,但記得標明文章出處:http://www.cnblogs.com/mao2080/

最近項目中的視頻功能,需要做到瀏覽器全兼容,所以之前用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在隱藏時,內部的狀態就存在丟失的情況,會導致一系列的問題。解決的辦法就是播一次就創建一次。關閉就清理。經測試,這種模式就再也不會有錯誤了

僅管如此,作為一個開源免費的產品,已經是相當不錯了。

參考網站

http://www.cnblogs.com/afrog/p/4115377.html

【轉】一款開源免費跨瀏覽器的視頻播放器--videojs使用介紹