我正在尝试将 seektotime 与 Pangesture 识别器一起使用。但它没有按预期进行搜索。
let totalTime = self.avPlayer.currentItem!.duration
print("time: \(CMTimeGetSeconds(totalTime))")
self.avPlayer.pause()
let touchDelta = swipeGesture.translationInView(self.view).x / CGFloat(CMTimeGetSeconds(totalTime))
let currentTime = CMTimeGetSeconds((avPlayer.currentItem?.currentTime())!) + Float64(touchDelta)
print(currentTime)
if currentTime >= 0 && currentTime <= CMTimeGetSeconds(totalTime) {
let newTime = CMTimeMakeWithSeconds(currentTime, Int32(NSEC_PER_SEC))
print(newTime)
self.avPlayer.seekToTime(newTime)
}
我在这里做错了什么?
最佳答案
想想这里这一行发生了什么:
let touchDelta = swipeGesture.translationInView(self.view).x / CGFloat(CMTimeGetSeconds(totalTime))
您将像素(仅在 x 轴上的平移)除以时间。这确实不是“增量”或绝对差异。这是某种比率。但这不是一个有任何意义的比率。然后,您只需将此比率添加到先前的 currentTime 即可获得新的 currentTime,因此您将每秒像素添加到像素,这不符合逻辑或有用的数字。
我们需要做的是从手势中获取 x 轴平移并对其应用 scale(这是一个比率)以获得有用的秒数来前进/后退AVPlayer。 x 轴平移以像素为单位,因此我们需要一个刻度来描述每个像素的秒数并将两者相乘以获得我们的秒数。适当的比例是视频中的总秒数与用户可以在手势中移动的像素总数之间的比率。将像素乘以(秒除以像素)得到一个以秒为单位的数字。在伪代码中:
scale = totalSeconds / totalPixels
timeDelta = translation * scale
currentTime = oldTime + timeDelta
所以我会像这样重写你的代码:
let totalTime = self.avPlayer.currentItem!.duration
print("time: \(CMTimeGetSeconds(totalTime))")
self.avPlayer.pause()
// BEGIN NEW CODE
let touchDelta = swipeGesture.translationInView(self.view).x
let scale = CGFloat(CMTimeGetSeconds(totalTime)) / self.view.bounds.width
let timeDelta = touchDelta * scale
let currentTime = CMTimeGetSeconds((avPlayer.currentItem?.currentTime())!) + Float64(timeDelta)
// END NEW CODE
print(currentTime)
if currentTime >= 0 && currentTime <= CMTimeGetSeconds(totalTime) {
let newTime = CMTimeMakeWithSeconds(currentTime, Int32(NSEC_PER_SEC))
print(newTime)
self.avPlayer.seekToTime(newTime)
}
关于ios - AVPlayer seektotime with Pangesturerecognizer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37309445/