0

如何在 HTML5 视频标签中按顺序播放两个视频?

在 Google Chrome 中,以下代码仅播放第一个介绍视频。

<html>
<head>
<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script>

var i = 0;
var sources = ['1.mp4', '2.mp4'];
videoElement.addEventListener('ended', function(){
   videoElement.src = sources[(++i)%sources.length];
   videoElement.load();
   videoElement.play();
}, true);

</script>

</head>
<body>
<video id="videoElement" width="640" height="360" autoplay="autoplay">
    <source src="intro.mp4" type="video/mp4"></source>
</video>

<body>
<html>
4

2 回答 2

4

浏览器应该使用您的 JavaScript 代码触发错误“videoElement is not defined”,您必须从 DOM 获取视频元素,而不是直接使用其 id。请将您的代码更改为

$(document).ready(function() {
    //place code inside jQuery ready event handler 
    //to ensure videoElement is available
    var i = 0;
    var sources = ['1.mp4', '2.mp4'];
    $('#videoElement').bind('ended', function() {
        //'this' is the DOM video element
        this.src = sources[i++ % sources.length];
        this.load();
        this.play();
    });
});
于 2011-11-08T16:25:59.757 回答
2

如果有人再次遇到这个问题,这是我对类似问题的解决方案——我需要播放第一个视频一次,然后循环播放第二个视频。我也支持.webm,.m4v.mp4.

这是我的 JS:

    $(document).ready(function(){
        var vid = document.getElementById("landing-video");
        vid.onplay = function() {
            var source=vid.currentSrc;
            folder = source.match(/(.+)(\/)/);
            ext = source.match(/(\.\w+)$/);
        };

        vid.onended = function() {
          $("#landing-video").attr({
            "src":folder[0]+"video-2"+ext[0],
            "loop":""
          });
        };
    });

这是我的 HTML:

    <video autoplay="" muted="" poster="" id="landing-video">
      <source src="my-folder/video-1.webm" type="video/webm">
      <source src="my-folder/video-1.m4v" type="video/x-m4v">
      <source src="my-folder/video-1.mp4" type="video/mp4">
    </video>

这可能会节省一些时间。

于 2016-04-18T19:40:29.497 回答