How to programmatically detect text track changes on iOS
This article describes how you can use the TextTrack API to detect text track changes. A text track "change" is triggered by enabling (or disabling) a subtitle or closed captions track.
Implementing this functionality is a common use-case for developers who want to build their own UI, and annotate the subtitle (or closed captions) track that is currently active.
Usage
The implementation of the iOS SDK applies to all iOS-based platforms, including iPadOS and tvOS.
The iOS SDK exposes the TextTrack API through player.textTracks.
This textTracks property is a TextTrackList.
This TextTrackList dispatches the events from the TextTrackListEventTypes.
The TextTrackListEventTypes contains the CHANGE event, as well as the ADD_TRACK and REMOVE_TRACK event.
The code below allows you to detect text track changes.
player?.textTracks.addEventListener(type: TextTrackListEventTypes.CHANGE, listener: { event in
let track: TextTrack = event.track as! TextTrack
let isEnabled = track.mode == .showing
print(track.label, track.kind, track.type, isEnabled)
})
The properties of a text track (e.g. mode, kind) are described in the TextTrack and Track API references.
Related articles
Are you reading this article because you are interested in subtitles and closed captions? Continue reading below.
- How to programmatically detect text tracks
- How to dynamically change the visible captions
- How to programmatically enable or disable text tracks
- How to insert subtitles
Refer to how to track ID3 cues if you are interested in timed metadata
(ID3, emsg, EventStream, EXT-X-DATERANGE, ...).
Are you reading this article because you are implementing a custom UI? Then you will find the following articles interesting: