如何在Tiktok之类的collectionView上快速播放视频数量?

问题描述

我正在构建一个视频列表视图(使用collectionView),例如Tiktok应用程序。我在imageView(为每个cellItem)上添加AVPlayerLayer并在其上播放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),以了解何时可以开始播放。您可以在根本不显示任何视频层之前执行此操作,然后将 ready AVPlayerItem对象传递给AVPlayer,这可能会带来加速视频的感觉。

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

此工具将检查播放列表的设置方式,并报告任何数量的错误,包括可能影响性能的错误。例如,如果初始比特率(播放器在弄清有关网络状况的数据等之前尝试播放的比特率)设置得太高,则可能导致加载时间过长。