Вопрос

Here is my function for determining if a given timecode in the buffer of an html5 video element (learned about this here).

I think there must be a faster way. Maybe a binary search over the start times?

I considered an interval tree, but the cost to maintain that data structure seems excessive given a system level data structure is provided.

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;
};
Это было полезно?

Решение

You can do this with a standard binary search that is slightly modified to test for matching a time range, rather than an exact match. It's not worth storing any kind of data structure, since the data will change quite frequently as additional data is buffered.

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;

There is a working demo at http://jsbin.com/vifedogi/1/edit?html,js,console,output

Note: you'll want to access the buffered object directly on the video element, not on the jQuery object, like var r = html5VideoEl.buffered;

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top