我正在尝试将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轴平移并对其应用比例(这是一个比率),以便获得有用的秒数来前进/后退
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 - 使用Pangesturerecognizer的AVPlayer seektotime,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37309445/