[iOS] AVPlayerで動画を倍速再生する
iOSでの標準動画プレイヤークラスとして、AVKitフレームワークのAVPlayerViewControllerというものがある。で、これはあくまでビューのコントローラで、再生まわりの制御機能はここにはなく、そこはAVPlayerクラスが担う。
https://developer.apple.com/documentation/avfoundation/avplayer
で、AVPlayerのリファレンスを漁りつつ倍速再生に関連するプロパティやメソッドを探すと、rateプロパティおよびplayImmediately(atRate:)メソッドが見つかる。
## rateプロパティ
https://developer.apple.com/documentation/avfoundation/avplayer/1388846-rate
公式リファレンスでのrateプロパティの解説にはこう書いてある。
A value of 0.0 pauses the video, while a value of 1.0 plays the current item at its natural rate. Rates other than 0.0 and 1.0 can be used if the associated player item returns true for the AVPlayerItem properties canPlaySlowForward or canPlayFastForward. Negative rate value ranges are supported if the player item returns true for the canPlayReverse, canPlaySlowReverse, and canPlayFastReverse properties.
(0.0 の値はビデオを一時停止し、1.0 の値は現在のアイテムを自然なレートで再生します。0.0 と 1.0 以外のレートは、関連するプレーヤ アイテムが AVPlayerItem プロパティの canPlaySlowForward または canPlayFastForward で true を返す場合に使用できます。プレーヤ アイテムが canPlayReverse、canPlaySlowReverse、および canPlayFastReverse プロパティに対して true を返す場合、負のレート値の範囲がサポートされています。)
つまり1以外の数値を渡すことで倍速再生(x0.5やx1.5)が可能そうである。
で、単にそれだけといえばそれだけなんだけど、これがなかなかクセが強かったのでメモしておく。
## AVPlayerItemのcanPlay〜
再掲するが、rateの解説には、
AVPlayerItem プロパティの canPlaySlowForward または canPlayFastForward で true を返す場合に使用できます。プレーヤ アイテムが canPlayReverse、canPlaySlowReverse、および canPlayFastReverse プロパティに対して true を返す場合、負のレート値の範囲がサポートされています。
とあった。
しかし手元で試したところ、これらがfalseが返してくるアイテムについても倍速再生は可能だった。
最後まで読んでいただきありがとうございます!もし参考になる部分があれば、スキを押していただけると励みになります。 Twitterもフォローしていただけたら嬉しいです。 https://twitter.com/shu223/