2014-03-31 64 views
0

這裏是我的函數,用於確定HTML5視頻元素的緩衝區中是否給定時間碼(瞭解到這個here)。優化在html5視頻緩衝區中搜索時間碼值?

我認爲必須有更快的方法。也許是在開始時間的二進制搜索?

我考慮了一個區間樹,但是提供了系統級數據結構,維護該數據結構的代價似乎過大了。

isTimecodeInBuffer = function(_tc) { 
    var r = $(html5VideoEl).buffered; 
    var i; 
    var iMax = r.length; 
    var within = false; 

    //todo: better seek here 
    for (i=0; i<iMax; ++i) { 
     if (_tc >= r.start(i) && _tc < r.end(i)) { 
      within = true; 
      break; 
     } 
    } 
    return within; 
}; 
+0

什麼是'$ (html5VideoEl).buffered'?你在使用圖書館嗎? – RobG

回答

1

可以與被稍微修改測試匹配的時間範圍,而不是精確的匹配標準二進制搜索做到這一點。不值得存儲任何類型的數據結構,因爲數據會隨着附加數據的緩存而頻繁更改。

function bufferedGreater(haystack, index, value) { 
    return haystack.end(index) <= value; 
} 

function bufferedLess(haystack, index, value) { 
    return haystack.start(index) > value; 
} 

function binarySearch(haystack, needle, greaterThan, lessThan) { 
    var minIndex = 0, 
     maxIndex = haystack.length - 1, 
     currentIndex; 

    while (minIndex <= maxIndex) { 
     currentIndex = Math.floor((minIndex + maxIndex)/2); 
     if (greaterThan(haystack, currentIndex, needle)) { 
      minIndex = currentIndex + 1; 
     } else if (lessThan(haystack, currentIndex, needle)) { 
      maxIndex = currentIndex - 1; 
     } else { 
      return currentIndex; 
     } 
    } 
    return -1; 
} 

var buffered = binarySearch(video.buffered, 10, bufferedGreater, bufferedLess) >= 0; 

有一個在http://jsbin.com/vifedogi/1/edit?html,js,console,output

注意一個工作演示:你要直接訪問buffered對象的視頻元素上,而不是jQuery的對象,比如var r = html5VideoEl.buffered;