从技术上讲,您不需要为此添加计时器。
只需添加属性即可
private var isUserDragingSlider: Bool = false
接下来,您需要设置一个滑块目标。
步骤1
self.timeSlider.addTarget(self, action: #selector(handleSliderChangeValue(slider:event:)), for: .allEvents)
在函数handleSliderChangeValue中,您需要添加以下内容:
步骤2
@objc
func handleSliderChangeValue(slider: UISlider, event: UIEvent) {
if let touchEvent = event.allTouches?.first {
switch touchEvent.phase {
case .began:
self.isUserDragingSlider = true
case .ended:
self.isUserDragingSlider = false
self.updateplayerWithSliderChangeValue()
default:
break
}
}
}
最后,您需要使用滑块选择的时间更新播放器。
第三步
func updateplayerWithSliderChangeValue() {
if let duration = player?.currentItem?.duration {
let totalSeconds = CMTimeGetSeconds(duration)
if !(totalSeconds.isNaN || totalSeconds.isInfinite) {
let newCurrentTime: TimeInterval = Double(self.timeSlider.value) * CMTimeGetSeconds(duration)
let seekToTime: CMTime = CMTimeMakeWithSeconds(newCurrentTime, preferredTimescale: 600)
self.player?.seek(to: seekToTime)
self.isUserDragingSlider.toggle()
}
}
}
最后一件事,您需要更新您的代码。视频正在更新您的滑块。
第四步
func setupSliderValue(_ seconds: Float64) {
guard !(seconds.isNaN || seconds.isInfinite) else {
return
}
if !isUserDragingSlider {
if let duration = self.player?.currentItem?.duration {
let durationInSeconds = CMTimeGetSeconds(duration)
self.timeSlider.value = Float(seconds / durationInSeconds)
}
}
}
这里的主要问题是,当我们移动滑块时,更新滑块(来自视频)和使用滑块更改更新视频之间存在冲突。
这就是为什么滑块不能正常工作的原因。当您使用isUserDragingSlider阻止从视频时间到滑块的更新时,一切都正常工作。