HTML5 video how to play two videos in one video element

后端 未结 1 1251
一向
一向 2021-01-31 19:39

I am trying to get two different videos to play in one video element, but putting two sources only plays the first one. Should i do this with jQuery? Code(HTML):



        
相关标签:
1条回答
  • 2021-01-31 19:52

    As I mentioned in the comments, the list of sources is not a playlist but a set of alternative sources. Once the browser finds one that is supported, the rest are ignored. You'll have to use JavaScript to achieve what you want (independently of doing it with one or two video tags).

    As in the question you mention only to have one video tag with the different sources, here is a possibility. The idea is the following:

    • Add an event listener to the end of the movie.
    • Change the video src with the src of the next source once the video is completed.
    • Note that this solution considers that all the source videos will be supported.

    In JavaScript, it would be something like this:

    var myvid = document.getElementById('myvideo');
    
    myvid.addEventListener('ended', function(e) {
      // get the active source and the next video source.
      // I set it so if there's no next, it loops to the first one
      var activesource = document.querySelector("#myvideo source.active");
      var nextsource = document.querySelector("#myvideo source.active + source") || document.querySelector("#myvideo source:first-child");
      
      // deactivate current source, and activate next one
      activesource.className = "";
      nextsource.className = "active";
      
      // update the video source and play
      myvid.src = nextsource.src;
      myvid.play();
    });
    <video id="myvideo" width="320" height="240" controls style="background:black">
      <source class="active" src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4" />
      <source src="http://www.w3schools.com/html/movie.mp4" type="video/mp4" />
    </video>

    The videos are from the W3Schools HTML5 video page.


    As specified by Kaiido in the comments, a simpler alternative would be to have the list of videos in an array in JavaScript and update the video source accordingly instead of having multiple sources directly under the video:

    var myvid = document.getElementById('myvideo');
    var myvids = [
      "http://www.w3schools.com/html/mov_bbb.mp4", 
      "http://www.w3schools.com/html/movie.mp4"
      ];
    var activeVideo = 0;
    
    myvid.addEventListener('ended', function(e) {
      // update the new active video index
      activeVideo = (++activeVideo) % myvids.length;
    
      // update the video source and play
      myvid.src = myvids[activeVideo];
      myvid.play();
    });
    <video src="http://www.w3schools.com/html/mov_bbb.mp4" id="myvideo" width="320" height="240" controls style="background:black">
    </video>

    You can also see it working on this JSFiddle: http://jsfiddle.net/bnzqkpza/

    0 讨论(0)
提交回复
热议问题