javascripthttp-live-streamingm3u8hls.js

Dynamically add segment urls to #EXTINF while generating manifest with JavaScript


I am generating a playlist manifest and playing the generated m3u8 file using HLS. I am looping over all the segment files to add their urls to #EXTINF:, but when I run my function, I get the error below, which means it's not properly receiving the urls:

[error] > 0 while loading data:application/x-mpegURL;base64,undefined

Here's my code:

segment_files = ["https://gib.s3.amazonaws.com/segment/first.ts", "https://gib.s3.amazonaws.com/segment/2nd.ts", "https://gib.s3.amazonaws.com/segment/first.ts"]
 function generate_manifest() {
    if (hls == undefined) {
      player = document.createElement("video");
      document.body.appendChild(player);

      player.pause();
      player.src = "";
      for (let ii = 0; ii < segment_files.length; i++) {
        var segment = segment_files[ii];
      }
      var manifestfile = btoa(
        `#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-PLAYLIST-TYPE:VOD\n#EXT-X-TARGETDURATION:11\n#EXTINF:10.000,\n${segment}\n#EXT-X-ENDLIST`
      );
    }
    if (Hls.isSupported()) {
      hls = new Hls({
        enableWorker: true,
        lowLatencyMode: true,
      });
      hls.attachMedia(player);
      hls.loadSource("data:application/x-mpegURL;base64," + manifestfile);
      player.muted = true;
      player.play();
    }
  }


Solution

  • somehow I bet you haven't read the basics of javascript yet:

    function generate_manifest() {
        if (hls == undefined) {
          player = document.createElement("video");
          document.body.appendChild(player);
    
          player.pause();
          player.src = "";
    -     for (let ii = 0; ii < segment_files.length; i++) {
    -       var segment = segment_files[ii];
    -     }
    -     var manifestfile = btoa(
    -       `#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-PLAYLIST-TYPE:VOD\n#EXT-X-TARGETDURATION:11\n#EXTINF:10.000,\n${segment}\n#EXT-X-ENDLIST`
    -     );
    
    +     const manifestfile = btoa(`#EXTM3U
    #EXT-X-VERSION:3
    #EXT-X-PLAYLIST-TYPE:VOD
    #EXT-X-TARGETDURATION:11
    #EXTINF:10.000,
    ${segment_files.join('\nEXTINF:10.000,\n')}
    #EXT-X-ENDLIST`)
        }
        if (Hls.isSupported()) {
          hls = new Hls({
            enableWorker: true,
            lowLatencyMode: true,
          });
          hls.attachMedia(player);
          hls.loadSource("data:application/x-mpegURL;base64," + manifestfile);
          player.muted = true;
          player.play();
        }
      }