LoginSignup
4
4

More than 5 years have passed since last update.

AVPlayerの字幕のオンオフをプログラムで制御する

Last updated at Posted at 2016-10-25

AVPlayerを使って、字幕のオンオフをプログラムから制御できます。字幕(Subtitle Track)のある動画の場合、OSデフォルトのプレイヤーの右下に字幕アイコンが表示されます。そこから手動で選択できるのですが、デフォルトで常にオンにしたい、カスタムViewで再生コントローラーもフルカスタマイズしたい場合もあるでしょう。

以下、AVPlayerViewController#player(AVPlayer)に対して、字幕オン・オフを行う場合(Swift3)

// バンドルから動画ファイルのURLを得る。ネット上のURLでもOK
let url = Bundle.main.url(forResource: "test01", withExtension: "m4v")!
let playerItem = AVPlayerItem(url: url)
// 字幕情報を得る
if let mediaSelectionGroup = playerItem.asset.mediaSelectionGroup(forMediaCharacteristic: AVMediaCharacteristicLegible) {
    // 字幕オプションが列挙される
    for option in mediaSelectionGroup.options {
        NSLog("option:%@", option.displayName)
    }
    // どれか適切なものを選択する。この場合、最初の字幕オプションを指定
    playerItem.select(mediaSelectionGroup.options.first, in: mediaSelectionGroup)
    // こうすると字幕をオフにできる
    playerItem.select(nil, in: mediaSelectionGroup)
}
self.player = AVPlayer(playerItem: playerItem)

動画への字幕付加はMacならSublerというアプリでできます。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4