0

this is my current script for displaying one caption language dynamically. I would like to add multiple languages which would means track.src = "<?php echo $_product->closed_caption_link; ?>"; will have video-german-de.vtt, video-english-en.vtt (comma delimiter) ... is there a simple way to do this

<?php if ($_product->closed_caption_link != ''): ?>
<script type="text/javascript">
var vidPlayer = document.getElementById('html5player');

vidPlayer.addEventListener("loadedmetadata", function() {
    track = document.createElement("track");
    track.kind = "captions";
    track.label = "English";
    track.srclang = "en";

    track.src = "<?php echo $_product->closed_caption_link; ?>";

    track.addEventListener("load", function() {
        this.mode = "showing";
        video.textTracks[0].mode = "showing"; // thanks Firefox
    });
    this.appendChild(track);
});
</script>
<?php endif;?>
misterben
  • 7,455
  • 2
  • 26
  • 47
acctman
  • 4,229
  • 30
  • 98
  • 142

1 Answers1

0

You can split the string, loop through it, and add multiple tracks. See How can I explode and trim whitespace?

You'll need more information to add the label and srclang. If the filenames are definitely always like your examples you could parse the srclang from the string, and perhaps have an array to look up the labels.

$langs = ["de" => "Deutsch", "en" => "English"];

foreach (array_map('trim', explode(',', $_product->closed_caption_link)) as &$src) {
    preg_match('/.*-(..).vtt/m', $src, $matches);
    $lang = $matches[1];
    $label = $langs[$lang];
    ...
}

If they're not that regular you'd need to think differently about how you store the caption tracks information, perhaps objects with the lang.

Since from the tag you're using Video.js, you should use Video'js addRemoteTextTracks() method to add tracks. You shouldn't modify the element directly once Video.js in initiated.

The JS part would be more like this:

var vidPlayer = videojs(document.getElementById('html5player'));

vidPlayer.on('loadedmetadata', function() {
    vidPlayer.addRemoteTextTrack({
         src: '<?= $src ?>',
         kind: 'captions',
         srcLang: '<?= $lang ?>',
         label: '<?= $label ?>'
    }, false);
});
misterben
  • 7,455
  • 2
  • 26
  • 47