I am using an AVPlayerView to display some local videos from my Apps Bundle directory. Now I want to add the ability to display subtitles for increased accessibility of my content.
Since I’m the programmer, filmmaker as well as the one who has to create the subtitles, I am open to any subtitle-formats & solutions. I discovered a few common formats (.srt, .scc), but however, I am wondering how to work with them "programmatically" using AVPlayer.
I initialize videos like:
let myVideoPlayer = AVQueuePlayer(url: URL(fileURLWithPath: "/myPath"))
If you play subtitled videos in QuickTime for example, it is enough to have both files (subtitles & video) in the same directory. I couldn’t find any hints or solutions like adding a subtitle-file-url to the AVPlayer, which I would expect. It seems that’s not the right approach?
Other threads mention that AVPlayers closedCaptionDisplayEnabled works well with Closed Caption tracks. But again that brings me to the question: How can I display subtitles with AVPlayer from a separate file (like .srt, .scc)?
I used ixany's suggestion (add subtitles to video file), but then I had to force AVPlayer to display subtitles using this code:
let playerItem = AVPlayerItem(asset: asset)
// group is like a popup button in QuickTime Player (like the one for subtitles
if let group = playerItem.asset.mediaSelectionGroup(forMediaCharacteristic: .legible) {
let locale = Locale(identifier: "en-EN")
// group.options are the items in that popup (like English, Forced English or Off)
// options holds a subset that matches the provided criteria
let options = AVMediaSelectionGroup.mediaSelectionOptions(from: group.options, with: locale)
// passing the one option to select(in:) is like selecting it in the popup
if let option = options.first {
playerItem.select(option, in: group)
}
}
And beware of testing this in simulator. For me this works only on real device.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With