0

I'm looking for solution to make a function, which forwards video in AVPlayer by for example 10 % of the video each time the user clicks on the button (10% + another 10 % next click + another 10 % next click etc) from the current state in video. So far, I've found a seek(to:CMTimeMakeWithSeconds(seconds: Float64, preferredTimescale: Int32) , however it moves the video TO a specific time every time, not BY a specific time.

Any suggestions, please?

lukas28277
  • 97
  • 1
  • 15

1 Answers1

3

You just need to do few simple math steps, in Swift 3 it should like something like this:

private func skipBy(percentage: Float64) {

    guard let durationTime = player.currentItem?.duration else { return }

    // Percentage of duration
    let percentageTime = CMTimeMultiplyByFloat64(durationTime, percentage)

    guard percentageTime.isValid && percentageTime.isNumeric else { return }

    // Percentage plust current time
    var targetTime = player.currentTime() + percentageTime
    targetTime = targetTime.convertScale(durationTime.timescale, method: .default)

    // Sanity checks
    guard targetTime.isValid && targetTime.isNumeric else { return }

    if targetTime > durationTime {
        targetTime = durationTime // seek to end
    }

    player.seek(to: targetTime)
}

For a great example of an AVPlayer in action, see the open source, community developed, unofficial WWDC app.

allenh
  • 6,582
  • 2
  • 24
  • 40