无法在 addEventListener 函数之外获取视频持续时间

Cannot get video duration outside addEventListener function

我有一个功能可以在上传视频之前将视频持续时间记录到控制台中。但是,我无法在 addEventListener 函数之外获取视频持续时间,因为它 returns 返回 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);

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

您正在将 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);运行sbeforeduration = video.duration;,因为video.addEventListener不会马上运行 它的功能。如果你确实需要对持续时间做一些事情,你可以在分配持续时间后 运行 它,就像这样:

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

您还可以使用其他异步数据管理技术之一: