需求是视频自动播放,并且列表预加载。
优化 1:
关闭自动播放:
videoView.shouldAutoplay = false
在 node 处于可见状态的时候播放,不可见时暂停:
override func didEnterVisibleState() {
super.didEnterVisibleState()
videoView.play()
if let currentTime = currentTime {
videoView.currentItem?.seek(to: currentTime)
}
}
override func didExitDisplayState() {
super.didExitDisplayState()
videoView.pause()
if let currentTime = videoView.currentItem?.currentTime() {
self.currentTime = .init(value: currentTime.value, timescale: currentTime.timescale)
}
}
优化 2:
关于获取视频时长:
通过AVURLAsset
的duration
获取时长会卡顿,然后就换了一种方案:
func videoNode(_ videoNode: ASVideoNode, didSetCurrentItem currentItem: AVPlayerItem) {
currentItem.addObserver(self, forKeyPath: "duration", options: .new, context: nil)
}
// MARK: - KVO
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let duration = self.videoView.currentItem?.duration else {
return
}
let value: Int = Int(duration.value)
let scale: Int = Int(duration.timescale)
let time = value / scale
let minutes = time / 60
let seconds = time % 60
let minutesString = String(format: "%.2d", minutes)
let secondsString = String(format: "%.2d", seconds)
durationLabel.attributedText = NSAttributedString.attributedString(string: "\(minutesString):\(secondsString)", font: .systemFont(ofSize: 12, weight: .medium), color: .white)
}
用了Texture
,我才知道什么叫做绝对丝滑。
从此以后别跟我说什么列表卡顿优化,都是渣渣。
网友评论