Categories
iOS tvOS

Playing with subtitles on iOS

For one of our project we have the requirements to change the look and feel of the subtitles with AVPlayer. The display is handled directly by iOS SDK but there are couple of things we can do.

Accessibility settings

In your iPhone, Open Settings > Accessibility > Subtitles & Captioning.


In this page you can customize the style of your subtitles which to be picked up by your AVPlayer.
You have a couple of predefined styles, but you can create your own one, and the style you select is going to be applied for all your instances of AVPlayer in all your applications.

More info: https://support.apple.com/guide/iphone/subtitles-captioning-iph3e2e23d1/ios

iOS settings
tvOS settings

⚠️ This is a pretty unknown settings for most of the people, so if you think this is important for your users you can let them know (in your application settings for example) and deeplink to settings page from there for example.

📺 This settings is also available on your Apple TV

Doing programatically

Programmatically, you are also able to change the subtitles styles with several parameters. For this, you need to use the API AVTextStyleRule.

  • foreground colour: kCMTextMarkupAttribute_ForegroundColorARGB
  • background colour: kCMTextMarkupAttribute_CharacterBackgroundColorARGB
  • font family: kCMTextMarkupAttribute_FontFamilyName
  • font size relative: kCMTextMarkupAttribute_RelativeFontSize
  • bold: kCMTextMarkupAttribute_BoldStyle
  • italic: kCMTextMarkupAttribute_ItalicStyle

Here is a small example on how to do this:

import AVFoundation

let textStyle:AVTextStyleRule = AVTextStyleRule(textMarkupAttributes: [
    kCMTextMarkupAttribute_CharacterBackgroundColorARGB as String: [0.5 ,1 ,0.0 ,0.0],
    kCMTextMarkupAttribute_ForegroundColorARGB as String: [1, 0.0, 0.0, 1.0],
    kCMTextMarkupAttribute_RelativeFontSize as String: 20,
])!

playerViewController.player?.currentItem?.textStyleRules = [textStyle]

📺 The same code is also running on the AVPlayer on tvOS, so you can customize the subtitles in the exact same way on tvOS as on iOS

AVTextStyleRule documentation:
https://developer.apple.com/documentation/avfoundation/avtextstylerule

Thank you for reading until here…  👊 Have a good week end…  🍺