js获取视频长度的3种方法

基本选择框:

 


       
       

获取方式:

第一种,监听onloadedmetadata :

function getTime() {undefined
    var file = document.getElementById("test").files[0];
    var video = document.createElement('video');
    video.preload = 'metadata';

    video.onloadedmetadata = function () {undefined
        var url = video.src
        if (url.startsWith("blob:")) {undefined
            url = url.substr(5);
        }
        window.URL.revokeObjectURL(url);
        var duration = video.duration;
        console.log("视频长度为:" + duration);
    }
    video.src = URL.createObjectURL(file);
}

第二种,监听oncanplay属性:

function getTime() {undefined
    var file = document.getElementById("test").files[0];
    var video = document.createElement('video');
    video.src = URL.createObjectURL(file);
    video.oncanplay = function () {undefined
        var duration = video.duration;
        var hour = parseInt(duration / 3600);
        var minute = parseInt(duration % 3600 / 60);
        var sec = parseInt(duration % 60);
        console.log("视频长度为:" + duration + "   " + hour + ":" + minute + ":" + sec);
    }
}

第三种,监听ondurationchange属性:

 function getTime() {undefined
        var file = document.getElementById("test").files[0];
        var video = document.createElement('video');
        video.src = URL.createObjectURL(file);
        video.onduratiοnchange= function () {undefined
            var duration = video.duration;
            var hour = parseInt(duration / 3600);
            var minute = parseInt(duration % 3600 / 60);
            var sec = parseInt(duration % 60);
            console.log("视频长度为:" + duration + "   " + hour + ":" + minute + ":" + sec);
        }
    }
 

你可能感兴趣的:(html,web前端,javascript,音视频,前端)