Search code examples
jqueryhtml5-videovideo.jsplaylist

video.js create dynamic playlist using json from database


I have some code that will display an html5 player using the video.js library. I want to create a playlist dynamically by using the json output from my db, so, to achieve this task, I've installed the videojs-playlist plugin.

I'm trying to generate a playlist using $.each() function, but without success. How I can process the json to create the playlist for the player? Another question is about the height and width of the player. How I can set it to the 100% width and height of the window?

This is the code I'm using:

  <video id='sc-player' class='video-js' controls preload='auto' autoplay width='1280' height='600' data-setup=''>
  </video>

  <script>
  $(document).ready(function(){

    const player = videojs('sc-player');

    $.ajax({
      type: 'GET',
      url: 'streamController.php?playlist',
      cache: false,
      success: function(response){

        var vid = JSON.parse(response);
        player.src(vid[0].url);

        $.each(vid, function(i){

          player.playlist([{
            sources: [{
              src: [i].url,
              type: 'video/mp4'
            }],
            poster: 'http://media.w3.org/2010/05/sintel/poster.png'
          }]);
          player.playlist.autoadvance(0);
        });
      }
    });
  });
  </script>


Solution

  • I've found a solution after searching here on SO:

      <video id='c-player' width='1280' height='619' class='video-js' controls autoplay prelaod ></video>
    
      <script>
    
      $(document).ready(function(){
    
        const player = videojs('c-player');
        var videosrc = [];
    
        $.ajax({
          type: 'GET',
          url: 'streamController.php?playlist',
          cache: false,
          success: function(response){
    
            var vid = JSON.parse(response);
            player.src(vid[0].url);
    
            for(var i = 0; i < vid.length; i++){
              var vidsUrl = vid[i].video_url;
              var posterUrl = vid[i].poster_url;
              videosrc.push({sources: [{src: vidsUrl, type: 'video/mp4'}],poster: posterUrl});
              //videosrc.push({sources: [{src: vidsUrl, type: 'video/mp4'}]});
            }
            player.playlist(videosrc);
            player.playlist.autoadvance(0);
            player.playlist.repeat(true);
    
          }
        });
      });
      </script>