Custom HLS loader

  抱歉,这篇文章有英文版

Our audio tracks are in HLS master.m3u8. There is no way to sort them. Could you add an option to sort the audio tracks alphabetically by language code, not by name, but by language code?

You can write your own manifest loader that will sort audio tracks in the desired order. This can be done using chatGPT with simple prompt "write a custom HLS manifest loader that sorts audio tracks by language code."

class CustomLoader extends Hls.DefaultConfig.loader {
   load(context, config, callbacks) {
      var onSuccess = callbacks.onSuccess;
      callbacks.onSuccess = function (response, stats, ctx, details) {
         if (context.type === 'manifest' && typeof response.data === 'string') {
            response = { data: reorderAudioByLang(response.data), url: response.url };
         }
         onSuccess(response, stats, ctx, details);
      };
      super.load(context, config, callbacks);
   }
}
function reorderAudioByLang(m3u8) {
   var lines = m3u8.split(/\r?\n/);
   var media = [], other = [];
   for (var i=0;i<lines.length;i++) {
      var L = lines[i];
      if (/^#EXT-X-MEDIA:TYPE=AUDIO/.test(L)) media.push(L); else other.push(L);
   }
   media.sort(function(a,b){
      function g(s){ var m = s.match(/LANGUAGE="([^"]*)"/i); return (m?m[1]:"").toLowerCase(); }
      var la=g(a), lb=g(b); return la>lb?1:la<lb?-1:0;
   });
   var out=[], mi=0;
   for (var i=0;i<lines.length;i++) {
      if (/^#EXT-X-MEDIA:TYPE=AUDIO/.test(lines[i])) {
         if (mi===0) for (var k=0;k<media.length;k++) out.push(media[k]);
         mi++;
      } else {
         out.push(lines[i]);
      }
   }
   return out.join("\n");
}

The CustomLoader class must be declared before initializing the player. Add its name to the player code using the hlsconfig parameter.

let player = new Playerjs({id: "player", file:m3u8, hlsconfig:{loader: CustomLoader}}

Demonstration


21.0.16
2025 © PlayerJS

登录

登录

免费注册

注册
注册即表示您同意服务条款
登录(如果您有帐户)

恢复密码

恢复
忘记电子邮件?联系我们