如何从JavaScript中的自定义对象构造函数返回视频时长?

时间:2019-01-14 20:24:48

标签: javascript constructor scope return html5-video

我正在尝试在自定义视频构造函数中获取视频时长。这是范围问题吗?我将如何继续并有效地做到这一点?视频显示正确,我似乎无法从函数外部访问视频的时长。

我猜这是一个初学者常见的简单范围问题。也许是关于addEventListener的使用?

<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8">
    <title>X</title>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script>
    $(document).ready(function(){

            var video_1 = new CustomVideo('0.mp4');
            video_1.createVideo();

            var videoDuration = video_1.durationVideo();
            console.log('durationVideo outside function = ' + videoDuration);
            });

            function CustomVideo(videoSrc){

                    this.videoSrc = videoSrc;
                    this.createVideo = createVideo;
                    this.durationVideo = durationVideo;

                    var myVideo;
                    var id_rand;
                    var id_myVideo;

                    function createVideo(){
                            myVideo = document.createElement('video');
                            id_rand = Math.floor(Math.random() * 999999);
                            id_myVideo = 'myVideo' + String(id_rand);
                            document.body.appendChild(myVideo);
                            myVideo.id = id_myVideo;
                            myVideo.src = videoSrc;

                    }

                    function durationVideo(){

            console.log('id_myVideo inside durationVideo =' + id_myVideo);
            var v = document.getElementById(id_myVideo);
            v.addEventListener( "loadedmetadata", function (e) {

                console.log('durationVideo inside func = ' + v.duration);
                return v.duration;

            }, false );
                    }
            }
    </script>
</head>

<body>
</body>

</html>

我希望通过评估durationVideo函数来获得视频的时长。

1 个答案:

答案 0 :(得分:0)

1-您的元素应返回以下html结构: Duration Example

  <video>
       <source src="0.mp4" type="video/mp4">
  </video>