问题描述: 在使用AVPlayer播放视频时,有时候会遇到寻找不正确的问题。即使指定了正确的时间点,AVPlayer也无法正确地跳转到目标时间点。
解决方法:
let targetTime = CMTime(seconds: 10, preferredTimescale: 1)
player.seek(to: targetTime) { (isCompleted) in
if isCompleted {
// 跳转完成后的操作
} else {
// 跳转失败的操作
}
}
在上述示例中,我们指定了要跳转到的时间点为10秒。在跳转完成后,可以根据isCompleted参数来判断跳转是否成功。
let targetTime = CMTime(seconds: 10, preferredTimescale: 1)
let observer = player.addBoundaryTimeObserver(forTimes: [NSValue(time: targetTime)], queue: .main) {
// 达到指定时间点后的操作
}
在上述示例中,我们指定了要监听的时间点为10秒。当播放器达到该时间点时,会执行闭包中的操作。
if let asset = player.currentItem?.asset {
let duration = asset.duration
let durationInSeconds = CMTimeGetSeconds(duration)
print("视频时长:\(durationInSeconds)秒")
}
在上述示例中,我们通过访问player.currentItem?.asset来获取视频资源,并使用CMTimeGetSeconds方法将duration转换为秒数进行打印。
通过以上解决方法,可以解决AVPlayer不正确寻找的问题。
上一篇:AVPlayer不起作用