Custom HLS loader

  Leider ist dieser Artikel auf Englisch verfügbar

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.1.2
2026 © PlayerJS

Kostenlos anmelden

Registrieren Sie sich
Mit der Anmeldung stimmen Sie den Nutzungsbedingungen
Login zu, wenn Sie ein Konto haben.

Passwort wiederherstellen

Wiederherstellen
E-Mail vergessen? Kontaktieren Sie uns