HTML5 Video - File Loading Complete Event?

前端 未结 3 1819
广开言路
广开言路 2020-12-23 18:20

I need to detect when a video file has completed loading. I\'m thinking I should use progress->buffer, but in the back of my mind, I remember reading that this was unreliabl

3条回答
  •  隐瞒了意图╮
    2020-12-23 18:38

    Here's a fleshed out implementation with Google's MDC-Web's mdc-linear-progress UI component.

    var doc = document;
    var bufferLengthDetector;
    var linearProgress;
    var mdc = window.mdc;
    mdc.autoInit();
    var video = doc.querySelector('video');
    
    if(doc.getElementById("footer-progress")){
        linearProgress = mdc.linearProgress.MDCLinearProgress.attachTo(doc.getElementById("footer-progress"));
    }
    
    if(video){
        
        video.addEventListener('timeupdate', function() {
            var percent = Math.floor((100 / video.duration) * video.currentTime);
            linearProgress.progress = percent/100;
        }, false);
        
        video.addEventListener('progress', function() {
            var duration = video.duration;
            if (duration > 0) {
                bufferLengthDetector = setInterval(readBuffer, 500);
            }
        });
    }
    
    function readBuffer(){
        var percent = video.buffered.end(video.buffered.length - 1) / video.duration;
        if (percent >= .9) {
            linearProgress.buffer = 1;
            clearInterval(bufferLengthDetector);
        }
        else {
            linearProgress.buffer = percent;
        }
    }
    html {
        height:100%;
    }
    body{
        margin: 0;
    }
    
    #footer-progress{
        position: fixed;
        bottom: 0;
        width: 100%;
        visibility: visible;
        opacity: 1;    
    }
    
    video {
        position: fixed;
        top: 50%;
        left: 50%;
        min-width: 100%;
        min-height: 100%;
        width: auto;
        height: auto;
        z-index: -100;
        transform: translateX(-50%) translateY(-50%);
        background: #212121;
        background-size: cover;
        transition: visibility 1s, opacity 1s linear;
        visibility: visible;
        opacity: 1;
    }
    
    
    
    
    
    
    
        
        
          
    
    

提交回复
热议问题