Adding subtitles to AVPlayer video

6.1k views Asked by At

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)?

3

There are 3 answers

0
ixany On BEST ANSWER

I ended up with the following workaround: Exporting my material from Final Cut Pro X as .m4v, creating subtitles manually with SRT Edit Pro and then adding them to the videofile with Subler, so I have just one file in the end. This way AVPlayer / QuickTime automatically detects the subtitle-track.

0
Miroslav Hrivik On

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)
if let group = playerItem.asset.mediaSelectionGroup(forMediaCharacteristic: .legible) {
    let locale = Locale(identifier: "en-EN")
    let options = AVMediaSelectionGroup.mediaSelectionOptions(from: group.options, with: locale)
    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.

3
Praveen Bishnoi On

This is perfect answer for adding close caption in AVPlayer. Need to just paste this code in your code. Thanks

let playerItem = AVPlayerItem(asset: asset)
if let group = playerItem.asset.mediaSelectionGroup(forMediaCharacteristic: .legible) {
    let locale = Locale(identifier: "en")
    let options = AVMediaSelectionGroup.mediaSelectionOptions(from: group.options, with: locale)
    if let option = options.first {
        playerItem.select(option, in: group)
    }
}