skip to content

In Media3's ExoPlayer, how do you make lessons prefer the learner's chosen audio language and cap video at SD with TrackSelectionParameters?

level: middleimportance: should knowfreq 35%

answer

  1. constraints, not picked tracks
  2. buildUpon on the current parameters
  3. language preference and a size ceiling
  4. applies to every playlist item
  5. overrides only match one track group

basics

~10 s

Copy the player's TrackSelectionParameters with buildUpon(), call setPreferredAudioLanguage("es") and setMaxVideoSizeSd(), and assign the result back. These are constraints, so they work before prepare() and apply to every lesson in the playlist.

solid answer

~40 s

Track selection in ExoPlayer is driven by `TrackSelectionParameters`. I take the current value, call `buildUpon()`, set `setPreferredAudioLanguage("es")` and `setMaxVideoSizeSd()`, which is `setMaxVideoSize(1279, 719)`, and assign it with `player.trackSelectionParameters = ...`. Because these are **constraints** rather than chosen tracks, I can set them before the player has prepared anything, and they carry over to every lesson in the playlist even when each lesson's tracks differ. Without them, ExoPlayer prefers audio matching the system locale and limits video to the physical display size. To build a language menu I read `player.currentTracks` or `onTracksChanged`, and only for a one-off pick do I add a `TrackSelectionOverride`, which applies only where the exact same track group exists. For screen-off listening, `setTrackTypeDisabled(C.TRACK_TYPE_VIDEO, true)` stops selecting video at all.

code

kotlin · 19 lines
kotlin
import androidx.media3.common.C
import androidx.media3.common.Player

fun Player.applyLearnerPreferences(audioLanguage: String, saveData: Boolean) {
    val builder = trackSelectionParameters.buildUpon()
        .setPreferredAudioLanguage(audioLanguage)
    if (saveData) {
        builder.setMaxVideoSizeSd()
    } else {
        builder.clearVideoSizeConstraints()
    }
    trackSelectionParameters = builder.build()
}

fun Player.setListeningOnly(listeningOnly: Boolean) {
    trackSelectionParameters = trackSelectionParameters.buildUpon()
        .setTrackTypeDisabled(C.TRACK_TYPE_VIDEO, listeningOnly)
        .build()
}

go deeper

for a junior

Recall the buildUpon, set, build and assign pattern, and the two calls for a language and an SD cap.

for a middle

Explain constraints versus overrides, why constraints survive playlist transitions, and what the defaults pick without any parameters.

for a senior

Show judgment on data and battery: when to cap resolution, when to disable video for listening, and how to detect a missing language from currentTracks.

for a principal

Decide which track preferences the product exposes and stores per learner, and keep them as constraints so every screen and playlist honours them.

## What track selection decides An HLS lesson usually offers several **tracks**: video in several resolutions and bitrates, audio in one or more languages, and subtitles. ExoPlayer groups them: a `Tracks.Group` holds tracks that present the same content in different formats, such as one video feed at five bitrates. Audio tracks in different languages are **not** grouped together, because they are not the same content. **Track selection** picks which tracks play. In ExoPlayer it is configured by **`TrackSelectionParameters`**, an immutable value you replace as a whole, and carried out by the player's `TrackSelector` (by default a `DefaultTrackSelector`). Within a selected video group, adaptive playback still switches between the allowed bitrates as bandwidth changes. ## Setting a language preference and a size cap The learner picks Spanish narration, and the app caps video at SD to save data on a phone plan: ```kotlin player.trackSelectionParameters = player.trackSelectionParameters .buildUpon() .setPreferredAudioLanguage("es") .setMaxVideoSizeSd() .build() ``` - `setPreferredAudioLanguage` takes a language tag; `setPreferredAudioLanguages` takes several in order of preference. - `setMaxVideoSizeSd()` is shorthand for `setMaxVideoSize(1279, 719)`; `setMaxVideoBitrate` caps by bitrate instead, and `clearVideoSizeConstraints()` removes the cap. - `setPreferredTextLanguage` does the same for subtitles. - The call can be made **before or during** playback; during playback the player reselects tracks for the current item. ## Constraints versus overrides Most options are **constraints**: they describe what you want without naming a track. That has three practical benefits: 1. They can be set before the player has prepared a lesson and learned its tracks. 2. They apply to **every item in the playlist**, even when the Spanish audio track's format differs from one lesson to the next. 3. They degrade gracefully: if no audio track is in Spanish, the selector still picks one, and by default `DefaultTrackSelector` will exceed the video size cap rather than select no video at all when no track fits it. An **override** names a concrete track: `setOverrideForType(TrackSelectionOverride(group.mediaTrackGroup, trackIndex))`. You build it from `player.currentTracks` after the tracks are known, and it applies **only to items containing exactly that `TrackGroup`**, so it can silently stop applying on the next lesson. Use overrides for an explicit "play this exact track" choice in a track menu, and constraints for standing preferences. ## The defaults With no parameters set, the defaults are not "anything goes": | Aspect | Default behaviour | |---|---| | Video size | No explicit maximum, but the viewport is limited to the device's physical display size, so a phone does not fetch a 4K rendition. | | Audio language | No preferred language; the selector favours tracks matching the system's locale languages. | | Track types | All enabled until you disable one. | ## Reading the available tracks To show a language picker, listen to `onTracksChanged(tracks)` or read `player.currentTracks` once the item is prepared. For each `Tracks.Group`, `type` gives the track type, `isTrackSupported(i)` says whether the device can decode a track, `isTrackSelected(i)` says whether it is playing, and `getTrackFormat(i)` returns its `Format`, including `language`. A supported track is supported on its own; it is not a promise that every supported group can play at the same time. ## Turning video off for screen-off listening When the learner locks the phone and only listens, keep decoding and downloading only audio: - `setTrackTypeDisabled(C.TRACK_TYPE_VIDEO, true)` disables video for all items until re-enabled. - An empty override, `addOverride(TrackSelectionOverride(group.mediaTrackGroup, listOf()))`, disables a single group instead. - Re-enable video with `setTrackTypeDisabled(C.TRACK_TYPE_VIDEO, false)` when the screen returns. ## Mistakes that silently undo a preference - Starting from `TrackSelectionParameters.Builder()` instead of `player.trackSelectionParameters.buildUpon()` throws away every preference already set, such as the SD cap when the learner only changes language. - Building the new value and forgetting to assign it back: the parameters are immutable, so nothing changes. - Selecting a track by index from a `Tracks` object read before the current item changed, which can point at another lesson's group. - Assuming the player remembers preferences across app restarts: they live in the player instance, so store the learner's choice and apply it each time a player is built. ## Where this stops These parameters choose among the renditions a stream already offers. How many renditions a lesson should have and how the player chooses a bitrate rung from measured bandwidth are questions of adaptive streaming design, not of this API.

  • Why might a TrackSelectionOverride chosen on lesson one have no effect on lesson two?
    An override names a specific `TrackGroup`, and it applies only to media items that contain exactly that group. Lesson two's Spanish audio is a different group even if it sounds the same, so the override does not match. A standing choice belongs in a constraint such as `setPreferredAudioLanguage`, which applies to every item.
  • What happens if the learner picks a language that a lesson does not offer?
    A preferred language is a constraint, not a requirement, so the selector still picks an audio track, favouring other preferences and the system's locale languages. The lesson plays rather than going silent; the app can compare `currentTracks` with the preference and tell the learner the narration is unavailable.

  • You must wait until onTracksChanged before setting any track preference.
  • An override chosen on one lesson carries over to every lesson in the playlist.
  • setMaxVideoSizeSd makes playback fail when a lesson has no SD rendition.
  • With no parameters set, ExoPlayer always fetches the highest resolution available.
  • You can mutate player.trackSelectionParameters in place without assigning it back.
  • Disabling the video track type stops the audio of that lesson too.