我有一个功能,可以在上传视频之前将视频时长记录到控制台中。但是,我无法在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设置为实际的视频持续时间,以便以后在脚本中使用?

最佳答案

您正在这段代码中将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

关于javascript - 无法在addEventListener函数之外获取视频时长,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50722323/

10-16 08:50