无法在addEventListener函数

时间:2018-06-06 13:58:43

标签: javascript variables video html5-video duration

我有一个功能,可以在上传视频之前将视频时长记录到控制台中。但是,我无法在addEventListener函数之外获取视频持续时间,因为它会返回NaN。尽管如此,在功能内部它成功记录了正确的视频持续时间,但如果我将其保存到变量中则无法获得正确的值。

视频时长功能

var duration = 0; // Set default variable for storing video duration
if(vfile.type == "video/webm" || vfile.type == "video/mp4" || vfile.type == "video/ogg" || vfile.type == "video/mov"){
        var video = document.createElement('video'); // Create video element
        video.preload = 'metadata'; // Set preload attribute to metadata
        window.URL.revokeObjectURL(video.src);
        video.addEventListener('durationchange', function() { // Check for duration
            console.log('Duration change', video.duration); // Successfully logs video duration into console e.g.: 13.012
            duration = video.duration; // Set duration variable to video.duration
        });
        console.log("Duration: ", duration); // Returns back 0
    }
    video.src = URL.createObjectURL(vfile);

如果我在duration函数之外将变量video.duration设置为addEventListener,则会返回NaN
总而言之,我如何将变量duration设置为实际的视频持续时间,以便以后在脚本中使用?

1 个答案:

答案 0 :(得分:1)

您在此代码中将video.duration分配给持续时间:

    video.addEventListener('durationchange', function() { // Check for duration
        console.log('Duration change', video.duration); // Successfully logs video duration into console e.g.: 13.012
        duration = video.duration; // Set duration variable to video.duration
    });
    console.log("Duration: ", duration); // Returns back 0

问题是console.log("Duration: ", duration);duration = video.duration;之前运行,因为video.addEventListener没有立即运行其功能。如果您确实需要对持续时间执行某些操作,则可以在分配持续时间后运行它,如下所示:

    video.addEventListener('durationchange', function() { // Check for duration
        duration = video.duration; // Set duration variable to video.duration
        someOtherFunction();
    });

您还可以使用其他异步数据管理技术之一:https://stackoverflow.com/a/14220323/6184972