<video src="blob:http://www.bilibili.com/d0823f0f-2b2a-4fd6-a93a-e4c82173c107"></video>
為何會(huì)有一個(gè) blob?直接點(diǎn)擊這個(gè)鏈接,返回了 404!什么情況?于是對(duì)此做了一番探索。
Examples
The following simple example loads a video chunk by chunk as fast as possible, playing it as soon as it can. This example was written by Nick Desaulniers and can be viewed live here.
var video = document.querySelector('video');
var assetURL = 'frag_bunny.mp4';
// Need to be specific for Blink regarding codecs
// ./mp4info frag_bunny.mp4 | grep Codec
var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) {
var mediaSource = new MediaSource();
//console.log(mediaSource.readyState); // closed
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', sourceOpen);
} else {
console.error('Unsupported MIME type or codec: ', mimeCodec);
}
function sourceOpen(_) {
//console.log(this.readyState); // open
var mediaSource = this;
var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
fetchAB(assetURL, function(buf) {
sourceBuffer.addEventListener('updateend', function(_) {
mediaSource.endOfStream();
video.play();
//console.log(mediaSource.readyState); // ended
});
sourceBuffer.appendBuffer(buf);
});
};
function fetchAB(url, cb) {
console.log(url);
var xhr = new XMLHttpRequest;
xhr.open('get', url);
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
cb(xhr.response);
};
xhr.send();
};
首先創(chuàng)建變量名為 video 的 DOM 對(duì)象和變量名為 mediaSource 的 MediaSource 對(duì)象。通過(guò)函數(shù) createObjectURL 來(lái)將 DOM::video 對(duì)象的屬性 src 和 mediaSource 進(jìn)行“連接”。接下來(lái),通過(guò)注冊(cè)事件 Event::sourceopen 來(lái)觸發(fā)當(dāng)上述“連接”結(jié)束之后的回調(diào)處理?;卣{(diào)處理就是需要賦值 視頻數(shù)據(jù) 的地方。 調(diào)用 MediaSource::addSourceBuffer 方法來(lái)構(gòu)建一個(gè)存放視頻數(shù)據(jù)的 sourceBuffer。 在往 sourceBuffer 中存放數(shù)據(jù)結(jié)束之后會(huì)觸發(fā)事件 Event::updateend 。通過(guò)注冊(cè)這個(gè)事件的回調(diào),可以知曉數(shù)據(jù)已經(jīng)加載完畢,然后關(guān)閉數(shù)據(jù)流,調(diào)用 Video::play 函數(shù)通知瀏覽器播放視頻。至此,整個(gè) Blob 運(yùn)行機(jī)制講解完畢。
W3C 上有明確關(guān)于 MediaSource 擴(kuò)展接口的文檔。擴(kuò)展文檔中是這么定義的, 它允許 JS 腳本動(dòng)態(tài)構(gòu)建媒體流和允許 JS 傳送媒體塊到 H5 媒體元素。這種接口的應(yīng)用可以讓 H5 播放器實(shí)現(xiàn)持續(xù)添加數(shù)據(jù)進(jìn)行播放。
綜上,這個(gè)只是 HTML5 提供的新特性,但是截止目前還是處于試驗(yàn)狀態(tài)。
特別注意
在上面示例中使用的視頻格式不是普通的 MP4 而是 FMP4。如果沒有注意到這個(gè)問(wèn)題,就可能造成:
HTML5 MediaSource works with some mp4 files and not with others (same codecs)。
解決方案:
It works fine if mp4 is fragmented.
You can do that using Bento4's mp4fragment tool.