美文网首页
AVPlayer的封装支持将已播放的数据片段保存到本地,纯swi

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

作者: 乌黑的太阳 | 来源:发表于2019-03-11 15:21 被阅读0次

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

    语言:swift 5.0

    效果

    shot.png

    架构

    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的封装支持将已播放的数据片段保存到本地,纯swi

          本文链接:https://www.haomeiwen.com/subject/tbcbpqtx.html