如何在视频完全加载时触发事件?
我已尝试使用以下方法让.loaded
和.total
进行比较和触发,但看起来像下面的scenerio控制台不停机日志未定义
video.addEventListener("progress", function(p){
console.log(p.loaded )
});
PS。 "视频"你猜可能是我的视频元素 PS2。不是HTML5 Video - Percentage Loaded?的重复 - 我不想"玩"视频,只加载它们。此链接的解决方案需要视频在自动播放或播放(加载它们)。
答案 0 :(得分:0)
没有任何事件可以让您知道完全下载视频的时间。这是因为浏览器希望知道消耗了多少数据,并尝试下载播放视频所需的最少量数据。
另一种可能的解决方案是使用普通的旧HTTP请求将视频文件下载为blob,并将其设置为视频元素的来源,如下所示:
/**
* Fetches a video file from a URL and returns a Promise that resolves with the file a Blob.
* @param {String} url - The URL where the video file should be fetched from.
* @returns {Promise} A Promise that resolves with the fetched video file as a Blob.
*/
function fetchVideo(url) {
return new Promise(function(resolve, reject) {
// Usual XMLHttpRequest setup.
var request = new XMLHttpRequest();
request.open('GET', url);
request.responseType = 'blob';
request.onload = function() {
// Check if request status code was successfull.
if (request.status === 200) {
// Resolve with request response.
resolve(request.response);
} else {
// Otherwise reject with a meaningfull message.
reject(new Error(req.statusText));
}
};
// Handle any network errors.
request.onerror = function() {
reject(new Error('Network error'));
};
// Send request.
request.send();
});
}
// Get the video element from the DOM.
var video = document.getElementById('video');
// Fetch video from remote server.
fetchVideo('https://d8d913s460fub.cloudfront.net/videoserver/cat-test-video-320x240.mp4')
.then(function(blob) {
// Create a source for the video element from the blob.
video.src = URL.createObjectURL(blob);
})
// Catch any error that occurs while fetching.
.catch(function(err) {
console.error('Unable to fetch video: ' + err.message);
});
<video id="video" controls autoplay></video>
答案 1 :(得分:-1)
您可以在此处查看解决方案HTML5 Video - Percentage Loaded?
检查百分比=已加载100%或完整下载视频。
答案 2 :(得分:-2)