PLaying two videos in sequence in Chrome by using the <video> tag

8.7k Views Asked by At

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

There are 2 best solutions below

2
On

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();
    });
});
0
On

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.