如何在收藏上快速播放大量视频像抖音一样查看



我正在构建一个类似抖音应用程序的视频列表视图(使用collectionView(。我在imageView上添加了AVPlayerLayer(针对每个cellItem(,并在上面播放AVPlayer,这需要一些时间来加载视频层。有人能建议我们如何在进入视频页面之前为播放器获取视频数据,以使视频页面更加流畅吗???

请检查下面的代码我做错了什么??

func setupVideoFor(url: String, completion: @escaping COMPLETION_HANDLER = {_ in}) {
if self.videoCache.object(forKey: url as NSString) != nil {
return
}

guard let URL = URL(string: url) else {
return
}

didVideoStartPlay = completion

let asset = AVURLAsset(url: URL)
let requestedKeys = ["playable"]
asset.loadValuesAsynchronously(forKeys: requestedKeys) { [weak self] in
guard let strongSelf = self else {
return
}
/**
Need to check whether asset loaded successfully, if not successful then don't create
AVPlayer and AVPlayerItem and return without caching the videocontainer,
so that, the assets can be tried to be downloaded again when need be.
*/
var error: NSError? = nil
let status = asset.statusOfValue(forKey: "playable", error: &error)
switch status {
case .loaded:
break
case .failed, .cancelled:
print("Failed to load asset successfully")
return
default:
print("Unkown state of asset")
return
}
let player = AVPlayer()
let item = AVPlayerItem(asset: asset)
DispatchQueue.main.async {
let videoContainer = VideoContainer(player: player, item: item, url: url)
strongSelf.videoCache.setObject(videoContainer, forKey: url as NSString)
videoContainer.player.replaceCurrentItem(with: videoContainer.playerItem)

/**
Try to play video again in case when playvideo method was called and
asset was not obtained, so, earlier video must have not run
*/
if strongSelf.videoURL == url, let layer = strongSelf.currentLayer {
strongSelf.duration = asset.duration
strongSelf.playVideo(withLayer: layer, url: url)
}
}
}
}

这取决于几个因素。。。

AVPlayer是控制AVPlayerItem发生什么的一种方式,而AVPlayerLayer只是它的显示层。

你想调查AVPlayerItem。您可以初始化多个AVPlayerItem对象,而无需将它们传递给AVPlayer。您可以观察它们的每个status属性(使用KVO(,以了解它们何时可以进行游戏。您可以在显示任何视频层之前执行此操作,然后将就绪AVPlayerItem对象传递给AVPlayer,这样可以获得加速视频的效果。

此外,您可以考虑查看视频的HLS清单。您可以使用mediastreamvalidator(以及其他工具(检查清单本身的错误。https://developer.apple.com/documentation/http_live_streaming/about_apple_s_http_live_streaming_tools

该工具将检查播放列表的设置方式,并报告任何数量的错误,包括可能影响性能的错误。例如,如果初始比特率(玩家在计算出网络条件等数据之前将尝试玩什么(设置得太高,这可能会导致加载时间过长。

相关内容

最新更新