【问题标题】:fire event when <video> is fully loaded<video> 完全加载时触发事件
【发布时间】:2015-11-17 23:30:27
【问题描述】:

如何在视频完全加载时触发事件?

我尝试了以下方法来获取 .loaded.total 进行比较和触发,但看起来像在以下场景控制台不间断日志未定义

    video.addEventListener("progress", function(p){
        console.log(p.loaded )
    }); 

ps。 “视频”是您可能猜到的我的视频元素 ps2。不是HTML5 Video - Percentage Loaded? 的副本 - 我不想“播放”视频,只加载它们。此链接的解决方案需要视频处于自动播放或播放状态(以加载它们)。

【问题讨论】:

  • @JonKoops 刚刚编辑了这个问题 - 不久又一次:我遇到了这种方法,但是当视频没有播放时,进度不会被触发。这是这里的主要问题之一。
  • 如果您不打算播放视频,那么您可能不应该使用video 元素。加载视频后,您希望对视频做什么?请相应地编辑您的问题。
  • 你搞清楚了吗?
  • @JonKoops 我想播放视频,但不是立即播放。
  • @JonKoops 我还没弄明白。

标签: javascript html google-chrome


【解决方案1】:

您可以在这里查看解决方案HTML5 Video - Percentage Loaded?

检查百分比 = 100% 已加载或完成下载视频。

【讨论】:

  • 如果您怀疑这个问题是重复的,请标记它。
  • 由于某种原因,如果视频未设置为自动播放,这对我不起作用。
  • 绝对不重复。
【解决方案2】:

没有任何事件可以让您知道视频何时已完全下载。这是因为浏览器希望了解消耗了多少数据,并会尝试下载播放视频所需的最少量数据。

另一种可能的解决方案是使用普通的旧 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);
      });
&lt;video id="video" controls autoplay&gt;&lt;/video&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多