2015-01-12 38 views
0

我需要加載視頻源,多種類型,從另一個網站,其上得到的回報文本鏈接到視頻。將視頻源從ajax動態加載到videojs或mediaelementjs中?

例如我打開:

http://www.getthisvideoexample.com?whichvideo=id0

它顯示在Web瀏覽器中的文本鏈接: http://someotherserver.com/somesubdomainrandomuniquenumber/thisisyourvideovalidforsometime.mp4

http://www.getthisvideoexample.com?whichvideo=id0&webm=true

,它顯示在Web瀏覽器中的文本鏈接: http://someotherserver.com/somesubdomainrandomuniquenumber/thisisyourvideovalidforsometime.webm

但是這個服務器有時,當負載較高時,將返回500錯誤。 所以我需要處理這一切。

讓我們例如:

<video id="myVideo"></video> 
var player = new MediaElementPlayer('#myVideo', { 
type: ['video/mp4', 'video/webm'], 
success: function (mediaElement, domObject) { 

    var sources = [ 
     { src: "HOW_TO_PUT_HERE_DYNAMICALLY_LOADED_MP4_LINK?", type: 'video/mp4' }, 
     { src: "HOW_TO_PUT_HERE_DYNAMICALLY_LOADED_WEBM_LINK?", type: 'video/webm' } 
    ]; 

    mediaElement.setSrc(sources); 
    mediaElement.load(); 
    mediaElement.play(); 
} 

});

還如何使它這樣,如果返回,而不是鏈接到視頻500或其他錯誤,代碼只會等待幾秒鐘,然後再試一次,或用文字顯示信息「再試一次,請等待......」 ? 謝謝。

回答

0

我會嘗試不同的方法。

我會在setInterval循環內(也許每隔2秒)發出一個ajax請求(使用jQuery.ajax())。如果AJAX請求,無論是

http://www.getthisvideoexample.com?whichvideo=id0 //返回一個MP4文件

...或

http://www.getthisvideoexample.com?whichvideo=id0&webm=true //返回一個WebM檔案

.. 。成功,然後清除間隔(clearInterval()),否則繼續嘗試,直到服務器成功響應(您可能需要設置清除一段時間的情況下,該服務器不可用後間隔的方法,否則就會在無限循環結束)

操作方法?

如果AJAX請求是成功的,那麼我會建立與response<video>標籤結構和標籤附加到一個視頻容器(<div>也許)

然後,我會結合MEJS到的新選擇附加標籤,如:

var URL = "http://www.getthisvideoexample.com?whichvideo=id0 "; // request video URL 
jQuery(document).ready(function ($) { 
    var getVideo = setInterval(function() { 
     $.ajax({ 
      url: URL, 
      cache: false, 
      dataType: "json", // or else 
      success: function (response) { 
       clearInterval(getVideo); // ends loop 
       // build video tag 
       // select proper type, based on response 
       var video = '<video id="video_player" width="320" height="240" controls>' + 
        '<source src="' + response + '" type="video/' + (response.indexOf("webm") == -1 ? 'mp4' : 'webm') + '" />' + 
        '</video>'; 
       // target container's selector 
       $("#videoContainer") 
       .html(video) // insert video tag 
       .find("#video_player") // find video selector after insertion 
       // bind MEJS 
       .mediaelementplayer({ 
        // MEJS options 
       }); 
      }, 
      error: function() { 
       // error in ajax, will try again in 2 seconds 
      } 
     }); 
    }, 2000); 
}); // ready 

JSFIDDLE

相關問題