简体   繁体   English

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

[英]How to return video duration from custom object constructor function in javascript?

I'm trying to obtain the video duration inside a custom video constructor function. 我正在尝试在自定义视频构造函数中获取视频时长。 Is this a problem of scope? 这是范围问题吗? How would I go on and do this efficiently? 我将如何继续并有效地做到这一点? The video is displayed correctly, I just can't seem to access it's duration from outside the function. 视频显示正确,我似乎无法从函数外部访问视频的时长。

I'm guessing this is a simple problem of scope common for begginers. 我猜这是初学者常见的范围内的一个简单问题。 Maybe regarding the use of the addEventListener? 也许关于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>

I expect to get the duration of the video by evaluating the durationVideo function. 我希望通过评估durationVideo函数来获得视频的时长。

1- Your element should return this html structure : Duration Example 1-您的元素应返回此html结构: 持续时间示例

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM