How to use MediaSelectionCriteria in AVKit

Hi, i am developing a media playback app and would like to set my own MediaSelectionCriteria for subtitles to the AVPlayer. However, this does not seem to work properly. Sometimes, the player displays the correct subtitle track and sometimes it displays no subtitles at all. The media file i use consists of a video track, a german audio track and an english subtitle track. My implementation is currently as follows:


let playerItem = AVPlayerItem(asset: AVAsset(url: url))
self.player = AVPlayer(playerItem: playerItem)
self.playerViewController!.player = player
let locales = ["de-DE", "de-AT", "de", "en-US", "en-GB", "en"]
let mediaSelectionCriteria = AVPlayerMediaSelectionCriteria(preferredLanguages: locales, preferredMediaCharacteristics: nil)
self.player!.setMediaSelectionCriteria(mediaSelectionCriteria, forMediaCharacteristic: .legible)
self.player!.play()
playerItem.asset.loadValuesAsynchronously(forKeys: ["availableMediaCharacteristicsWithMediaSelectionOptions"]) {
            for characteristic in playerItem.asset.availableMediaCharacteristicsWithMediaSelectionOptions {
                if [.legible].contains(characteristic), let group = playerItem.asset.mediaSelectionGroup(forMediaCharacteristic: characteristic) {
                    DispatchQueue.main.sync {
                        playerItem.selectMediaOptionAutomatically(in: group)
                    }
                }
            }
        }

Replies

The documentation for "selectMediaOptionAutomatically(in:)" says:


"This method has no effect unless the appliesMediaSelectionCriteriaAutomatically property of the associated AVPlayer is true and unless automatic media selection has previously been overridden by invoking select(_:in:)."

Does that mean, I have to set appliesMediaSelectionCriteriaAutomatically to false and I must not invoke select(_:in:) ?

The default for "appliesMediaSelectionCriteriaAutomatically" is true (for most iOS versions), but since you haven't used "select(_:in:)", your "selectMediaOptionAutomatically(in:)" is being ignored.


Is there a reason you invoke this after "play()"? It might make sense to load the asset keys first, then start playback.