代码之家  ›  专栏  ›  技术社区  ›  lukas28277

AVPlayer按特定时间跳过

  •  0
  • lukas28277  · 技术社区  · 7 年前

    我正在寻找一个解决方案来制作一个功能,该功能在AVPlayer中转发视频,例如用户每次点击按钮时(10%+下一次点击10%+下一次点击10%+下一次点击10%等),从视频中的当前状态转发视频。到目前为止,我发现了一个 seek(to:CMTimeMakeWithSeconds(seconds: Float64, preferredTimescale: Int32) 但是,它每次都将视频移动到特定的时间,而不是特定的时间。

    1 回复  |  直到 7 年前
        1
  •  3
  •   allenh    7 年前

    你只需要做几个简单的数学步骤,在Swift 3中应该是这样的:

    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)
    }
    

    关于AVPlayer的一个很好的例子,请参阅开源的、社区开发的、非官方的 WWDC app