Monday, September 28, 2015

Play multi video by canvas no interrupt

Demo

window.requestAnimationFrame = (function(){    return  window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame    ||
        function( callback ){            window.setTimeout(callback, 1000 / 60);
        };
})();

var ctx = canvas.getContext('2d'),
    w = canvas.width,
    h = canvas.height,
    video1 = document.createElement('video'),
    video2 = document.createElement('video'),
    isVideo1 = false,
    list = [],
    current = 0,
    isPlaying = false,

/// watermark    wm = document.createElement('canvas'),
    wctx = wm.getContext('2d'),
    wtxt = 'AbdiasSoftware.com video player demo';

wm.width = 380;
wm.height = 20;
wctx.font = 'bold 20px Arial';
wctx.fillStyle = 'rgba(255,255,255, 0.5)';
wctx.textBaseline = 'top';
wctx.fillText(wtxt, 0, 0);

video1.addEventListener('ended', play, false);
video2.addEventListener('ended', play, false);

addVideo('http://www.w3schools.com/html/mov_bbb.mp4', 'http://www.w3schools.com/html/mov_bbb.ogg');

addVideo('http://media.sublimevideo.net/v/next15-sublime_360p.mp4', 'http://media.sublimevideo.net/v/next15-sublime_360p.webm');

getVideo(list[0], play);

/// start looprender();

function play(){
    var video = (isVideo1 === false ? video1 : video2),
        next = current;

    isVideo1 = !isVideo1;

    next++;
    if (next > list.length - 1) next = 0;

    if (list.length > 0) getVideo(list[next]);

    /// start video    video.play();
    isPlaying = true;

    current = next;
}
function render() {    if (isPlaying) {        var video = (isVideo1 === true ? video1 : video2);
        ctx.drawImage(video, 0, 0, w, h);
        ctx.drawImage(wm, 8, 8);
    }    requestAnimationFrame(render);
}
function addVideo(urlMP4, url) {    list.push({        urlMP4: urlMP4,
        url: url,
        isReady: false    })}
function getVideo(vid, callback) {
    var video = (isVideo1 === false ? video1 : video2),
        me = this;

    video.addEventListener('canplay', canPlay, false);;

    function canPlay(e) {        video.removeEventListener('canplay', canPlay, false);
        vid.isReady = true;
        if (typeof callback === 'function')            callback(vid);
    }
    if (video.canPlayType("video/mp4").replace('no', '').length > 0) {        video.src = vid.urlMP4;
    } else {        video.src = vid.url;
    }}