LoginSignup
53
54

More than 5 years have passed since last update.

AVPlayerを秒指定でシークする

Posted at

AVplayerを司る時間の概念がCMTimeの為、非常に分かりにくいのがAVPlayerの良くないところです。

基礎知識

ビデオの長さを取得する

let duration = player.currentItem?.asset.duration
これでプレイヤーにセットされているアセットの再生時間が取得出来ます。
型はCMTime型です。

CMTimeを秒に変換する

let maxTime = CMTimeGetSeconds(duration)
CMTimeGetSecondsを取得することで、現実で何秒間のアセットなのかを取得することができます。
上記の例では、ビデオの長さを秒に変換しています。

秒をCMTimeに変換する

let interval:CMTime = CMTimeMakeWithSeconds(0.01, Int32(NSEC_PER_SEC))
秒で計算後、playerにセットする場合はまたCMTimeに戻す必要があります。
CMTimeMakeWithSecondsでは、秒数とタイムスケールを指定します。
タイムスケールは難しいので理解する必要はありません。
Int32(NSEC_PER_SEC)を指定することで、現実の時間と同じ大きさのタイムスケールが指定されます。

1.3秒後にシークしてみよう

var currentTime:Float64 = CMTimeGetSeconds(player.currentTime())
currentTime += 1.3
player.seekToTime(CMTimeMakeWithSeconds(currentTime,Int32(NSEC_PER_SEC)), toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)

現在時刻を秒で取得したら、普通に1.3を加算します。
あとはCMTimeに戻してseekToTimeでシークすればOKです。
tileranceBefore/Afterを指定しないと1秒単位でしかシークされないので注意。

53
54
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
53
54