logo

How to dynamically change the visible captions?

When working with the captions / text-track options, you can dynamically change the currently selected language (or set a default language) using following methods.

This method assumes that you are using text-tracks that are loaded with the manifest. If you add the text-track separately, you can just use this API: TextTrackDescription

Table of Contents

Step-by-step guide

1. Create a new function inside the browser

Web SDK
function setLanguage(player, language) {
        // Disable all text tracks that are currently active
    player.textTracks.filter(function(x) { if (x.label !== 'disabled') { return x }}).forEach(function(x){x.mode='disabled';});
            // Enable the text track for a specific language. Note: here i searched on the label, you can also do x.language for the ISO 3 letter language code
    player.textTracks.filter(function(x) { if (x.label == language) { return x }})[0].mode = 'showing'
}
iOS SDK
TO BE TESTED
private func setLanguage(player: THEOplayer, language: String) {
    let array = player.textTracks as! Array<TextTrack>
    //Disable all current active textTracks
    _ = array.filter { $0.label != "disabled" }.forEach { $0.mode == TextTrackMode.disabled }
    //Enable the text track for a specific language.
    var textTrackToActivate = array.filter { $0.label == language }[0]
    textTrackToActivate.mode = TextTrackMode.showing
}	
Android SDK

WIP

Roku SDK

In the following example we are iterating through all available text tracks. Once we found a track with a desired language, we simply set the mode to "showing". After that we have to simply assign testTracks object to a proper THEOplayer attribute. This is all you have to do to make a desired text track visible. Of course we can modify a visible text track during the video playback.

function setCaptionsLanguage(language as String)
  textTracks = m.player.textTracks
  for i = textTracks.count() - 1 to 0 step -1
    if textTracks[i].kind = "captions" and textTracks[i].language = language then
      if m.fullScreen then
        textTracks[i].mode = "showing"
      else
        textTracks[i].mode = "hidden"
      end if
    else
      textTracks[i].mode = "disabled"
    end if
  end for
  'assigment of new roAssociativeArray is required because roku deep-copied roAssociativeArray through fields (pass-by-value)
  'read more : <https://developer.roku.com/en-gb/docs/developer-program/performance-guide/optimization-techniques.md#OptimizationTechniques-DataFlow>
  m.player.textTracks = textTracks
end function

2. Call the function using the language label (or 3-letter-language code if you change x.label to x.language)

github
Make sure to follow us on GitHub!
THEO-logo-white
twitter
facebook
linkedin
Copyright © 2022. All Rights Reserved.
Leuven
New York
Singapore
Barcelona