AVPlayer的封装支持将已播放的数据片段保存到本地,纯swift

github: https://github.com/ZhongshanHuang/VideoPlayer

语言:swift 5.0

效果

AVPlayer的封装支持将已播放的数据片段保存到本地,纯swift_第1张图片
shot.png

架构

AVPlayer的封装支持将已播放的数据片段保存到本地,纯swift_第2张图片
architecture.png

遇到过的坑

1、只有将播放地址变成“非法”的、系统无法处理的地址,才会调用AVAssetResourceLoaderDelegate 的方法

 /// 播放视频
    func play(with url: URL, needCache: Bool = false) {
        var item: AVPlayerItem
        if needCache {
            let url = URL(string: kScheme + url.absoluteString)!
            let urlAsset = AVURLAsset(url: url)
            urlAsset.resourceLoader.setDelegate(loaderDelegate, queue: DispatchQueue.main)
            item = AVPlayerItem(asset: urlAsset)
        } else {
            item = AVPlayerItem(url: url)
        }
        play(with: item)
    }

2、avplayer的seek跳转播放
最开始我将preferredTimescale 设置为了1CMTime(seconds: seconds, preferredTimescale: 1) ,导致completion回调很慢(跳转后可能过1分钟才能回调),找了一天多才发现是time的时间精度问题,设置为600后完美解决

    /// 跳转
    func seekToTime(_ timeInterval: TimeInterval, completionHandler: ((Bool) -> Void)? = nil) {
        guard let playItem = playerItem else {
            completionHandler?(false)
            return
        }
        
        let seconds = (playItem.duration.seconds - timeInterval) > 0 ? timeInterval : playItem.duration.seconds
        if let completionHandler = completionHandler {
            player.seek(to: CMTime(seconds: seconds, preferredTimescale: 600), completionHandler: completionHandler)
        } else {
            player.seek(to: CMTime(seconds: seconds, preferredTimescale: 600))
        }
    }

你可能感兴趣的:(AVPlayer的封装支持将已播放的数据片段保存到本地,纯swift)