見出し画像

[iOS] AVPlayerで動画を倍速再生する

iOSでの標準動画プレイヤークラスとして、AVKitフレームワークのAVPlayerViewControllerというものがある。で、これはあくまでビューのコントローラで、再生まわりの制御機能はここにはなく、そこはAVPlayerクラスが担う。

画像1

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が返してくるアイテムについても倍速再生は可能だった

ここから先は

1,864字
文章やサンプルコードは多少荒削りかもしれませんが、ブログや書籍にはまだ書いていないことを日々大量に載せています。たったの400円で、すぐに購読解除してもその月は過去記事もさかのぼって読めるので、少しでも気になる内容がある方にはオトクかと思います。

技術的なメモやサンプルコード、思いついたアイデア、考えたこと、お金の話等々、頭をよぎった諸々を気軽に垂れ流しています。

最後まで読んでいただきありがとうございます!もし参考になる部分があれば、スキを押していただけると励みになります。 Twitterもフォローしていただけたら嬉しいです。 https://twitter.com/shu223/