How to turn On/OFF closed captions in HLS Streaming URL in Exoplayer?

Kanagalingam picture Kanagalingam · Feb 24, 2017 · Viewed 7.7k times · Source

I am using Exoplayer Version 2.0.4 to play HLS Streams(.m3u8). My HLS streams contains the closed captions with it. How can i control the closed captions with exoplayer? Is it feasible to hide/show the subtitle when required and change the placement of the subtitle layout if required?

Answer

Taylor Newton picture Taylor Newton · Sep 18, 2017

I was able to control caption selection in ExoPlayer 2 using a DefaultTrackSelector. The code below was modified based on the ExoPlayer 2 Demo's TrackSelectionHelper class, which should be referenced for more implementation details.

To turn captions off, you need to disable the renderer for the text tracks and clear the selection overrides.

trackSelector.setRendererDisabled(TRACK_TEXT, true);
trackSelector.clearSelectionOverrides();

TRACK_TEXT is a local static variable I created representing the index of the text tracks (2), in relation to video/audio tracks. I believe that SelectionOverrides are just programmatically specified track selections.

To enable the tracks again, you need to enable the renderer for text tracks, and then set up a new SelectionOverride for your desired text track. Before you can do this, you need to get the TrackGroupArray of the currently mapped text tracks from your DefaultTrackSelector.

MappingTrackSelector.MappedTrackInfo mappedTrackInfo = trackSelector.getCurrentMappedTrackInfo();
TrackGroupArray textGroups = mappedTrackInfo.getTrackGroups(TRACK_TEXT); // list of captions
int groupIndex = 1; // index of desired caption track within the textGroups array

trackSelector.setRendererDisabled(TRACK_TEXT, false);
MappingTrackSelector.SelectionOverride override = 
    new MappingTrackSelector.SelectionOverride(fixedFactory, groupIndex, 0);
trackSelector.setSelectionOverride(TRACK_TEXT, textGroups, override);

For more implementation details (e.g., initializing the trackSelector and fixedFactory), check out the ExoPlayer 2 Demo.

You can use a SubtitleView to position the captions within your layout. Your class will need to implement TextRenderer.Output and override the onCues() method.

@Override
public void onCues(List<Cue> cues) {
    if (subtitleView != null) {
        subtitleView.onCues(cues);
    }
}