0

How do I play two videos in a sequence in the HTML5 video tag?

In Google Chrome, the following code plays only the first intro video.

<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>

2 Answers2

4

Browser should fire error 'videoElement is not defined' with your JavaScript code, you must get video element from DOM instead of using its id directly. Please change your code to

$(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();
    });
});
ExpExc
  • 3,828
  • 1
  • 15
  • 20
  • Thanks that was very helpful, it worked...except that the last two videos now play endlessly. What's causing it? How to stop after the last video has finished playing? It's driving me crazy. – Frankie 'Moodurian' Kam May 15 '12 at 17:18
  • 2
    I know this question is old and you asked this ages ago but it is due to the modulo operator on this line sources[i++ % sources.length]. As i increments it makes sure that it does not go past sources.length. When it does it loops back around. When i = 2, 2 % 2 = 0. This means it will constantly repeat index 0 and index 1 of sources. – BrandonKowalski Jul 16 '13 at 20:04
2

In case someone came across this question again, here is my solution to similar problem-I needed to play first video once and then second video in a loop. I also have support for .webm, .m4v and .mp4.

This is my 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":""
          });
        };
    });

And this is my 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>

This might save someone some time.

Juraj.Lorinc
  • 503
  • 6
  • 26