我有一个功能,可以在上传视频之前将视频持续时间记录到控制台中。但是,我无法在 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);
如果我在 addEventListener
函数之外将变量 duration
设置为 video.duration
,它会返回 NaN
。< br/>
总而言之,如何将变量 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: ",uration);
在 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/