一、思路

 

首先,我们视频表中播放视频,并不一定需要每个cell添加一个player,这样既要控制每个cellplayer,同时还占用内存我们只需用一个player可以实现在列表中的某个区域播放视频,大致思路如下

1.监听列表滚动

2.在列表设置一个最高点,一个最低点,从而确定一个播放范围

3.当用户滑动列表使cell进入播放范围时,将player添加到要播放控件中进行视频播放。

4.滑动到下一个要播放的cell时,移除当前正在播放或者离开屏幕player,将player添加到新的播放控件中。

二、具体实现

1.协议VideoPlayable

protocol VideoPlayable: UIView {
    ///播放器容器
    var viewToContainVideo: UIView {get}
    ///设置播放url
    var urlToPlay: URL? {get}
    ///播放状态改变
    func videoStatusChanged(changeTo isPlaying: Bool)
    ///播放时间改变
    func videoPlayTimeChanged(changeTo playTime: Float64)
}

继承VideoPlayable的控件即可在上面播放视频,同时可以根据需求声明属性方法比如这里需要获取视频的播放进度,就声明了 videoPlayTimeChanged监听视频的播放

2.协议VideoListPlayable

protocol VideoListPlayable: UIScrollView {
    var visibleViews: [VideoPlayable] {get}
}

extension UITableView: VideoListPlayable {
    var visibleViews: [VideoPlayable] {
        let views: [VideoPlayable] = visibleCells.compactMap({ $0 as? VideoPlayable })
        return views
    }
}

extension UICollectionView: VideoListPlayable {
    var visibleViews: [VideoPlayable] {
        let views: [VideoPlayable] = visibleCells.compactMap({ $0 as? VideoPlayable })
        return views
    }
}

继承了VideoListPlayable的控件在监听列表滚动时,即可对视频播放进行处理

3.创建Manager

class GXRCWVideoListAutoPlayManager {
    
    static let shared = GXRCWVideoListAutoPlayManager()
    
    private var playerVC: AVPlayerViewController = AVPlayerViewController()
    private var preOffsetY: CGFloat = 0
    private var currentPlayingView: VideoPlayable?
    
    private init() {
        playerVC.player = AVPlayer()
//        playerVC.showsPlaybackControls = false
        playerVC.view.backgroundColor = .clear
        
        //暂停播放器
        _ = NotificationCenter.default.rx
            .notification(Notification.Name(NotificationNameInfo.kPuseVideoPlayer))
//            .take(until: self.rx.deallocated)
            .subscribe(onNext: { _ in
                self.playerVC.player?.pause()
            })
    }
    
    func scrollViewDidScroll(_ scrollView: VideoListPlayable) {

        let currentOffsetY = scrollView.contentOffset.y
        
        //设置播放范围
        let minY = scrollView.frame.height * 0.2
        let maxY = scrollView.frame.height * 0.75
        
        // 获取scrollView 自动播放区域内的视频
        let autoPlayableViews = scrollView.visibleViews.filter { view in
            guard let relativeRect = relativeRect(view: view.viewToContainVideo, relativeTo: scrollView), view.urlToPlay != nil else {return false}
            let containerCenterY = relativeRect.minY + relativeRect.height / 2
            return (containerCenterY &gt; minY &amp;&amp; containerCenterY < maxY)
        }
        
        guard let first = autoPlayableViews.first else {
            // 没有需要自动播放的视频
            // 移除当前正在离开/已经离开屏幕的视频
            removeCurrentVideoIfLeavingScreen(scrollView: scrollView)
            preOffsetY = currentOffsetY
            return
        }

        // 取出需要自动播放的视频
        let viewToPlay: VideoPlayable = autoPlayableViews.reduce(first) { (result, view) in
            let isScrollToUpper = currentOffsetY < preOffsetY
            return result.frame.maxY > view.frame.maxY ? (isScrollToUpper ? view : result) : (isScrollToUpper ? result : view)
        }
        
        if let currentPlayingView = currentPlayingView, viewToPlay as UIView == currentPlayingView {
            // 满足条件的视频正在播放中
            preOffsetY = currentOffsetY
            return
        }
        removeCurrentVideo(on: scrollView)
        addPlayerView(to: viewToPlay, on: scrollView)
        preOffsetY = currentOffsetY
    }
    
    func play(at videoView: VideoPlayable, on scrollView: VideoListPlayable) {
        removeCurrentVideo(on: scrollView)
        addPlayerView(to: videoView, on: scrollView)
    }
}

manager连通列表cell实现播放的中间者,也是实现列表视频播放的核心,如需修改播放的范围修改minYmaxY的值即可。

4.私有方法

private extension GXRCWVideoListAutoPlayManager {

    func relativeRect(view: UIView, relativeTo scrollView: VideoListPlayable) -> CGRect? {
        // 计算 view 相对于 scrollView 的位置
        guard let scrollViewSuperView = scrollView.superview, let containerSuperview = view.superview else {return nil}
        let containerViewRect = containerSuperview.convert(view.frame, to: scrollViewSuperView)
        let relativeRect = CGRect(origin: CGPoint(x: containerViewRect.minX - scrollView.frame.minX, y: containerViewRect.minY - scrollView.frame.minY), size: containerViewRect.size)
        return relativeRect
    }
    
    func addPlayerView(to view: VideoPlayable, on scrollView: VideoListPlayable) {

        guard let url = view.urlToPlay else {
            return
        }

        let avItem = AVPlayerItem(url: url)
        let avPlayer = AVPlayer(playerItem: avItem)
        playerVC.player = avPlayer
        avPlayer.isMuted = true//默认开启静音
        avPlayer.play()
        avPlayer.addPeriodicTimeObserver(forInterval: CMTime(value: CMTimeValue(1.0), timescale: CMTimeScale(1.0)), queue: .main) { time in
            //监听视频播放进度
            view.videoPlayTimeChanged(changeTo: CMTimeGetSeconds(time))
        }

        view.videoStatusChanged(changeTo: true)

        let containerView = view.viewToContainVideo
        containerView.addSubview(playerVC.view)

        playerVC.view.translatesAutoresizingMaskIntoConstraints = false
        playerVC.view.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
        playerVC.view.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
        playerVC.view.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
        playerVC.view.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true

        currentPlayingView = view
        
        playerVC.showsPlaybackControls = true
    }
    
    func removeCurrentVideoIfLeavingScreen(scrollView: VideoListPlayable) {
        playerVC.showsPlaybackControls = false
        guard let view = currentPlayingView, let relativeRect = relativeRect(view: view, relativeTo: scrollView) else {
            return
        }
        let currentOffsetY = scrollView.contentOffset.y
        let containerCenterY = relativeRect.minY + relativeRect.height / 2
        if (currentOffsetY > preOffsetY &amp;& containerCenterY <= 0) || (currentOffsetY < preOffsetY && containerCenterY >= scrollView.frame.height) {
            removeCurrentVideo(on: scrollView)
        }
    }

    func removeCurrentVideo(on scrollView: VideoListPlayable) {
        playerVC.player = nil
        playerVC.view.removeFromSuperview()
        currentPlayingView?.videoStatusChanged(changeTo: false)
        currentPlayingView = nil
    }
}

三、使用示例

1.列表监听滚动

extension DiscoverSearchDynamicsListView: UIScrollViewDelegate{
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        GXRCWVideoListAutoPlayManager.shared.scrollViewDidScroll(self)
    }
}

2.cell实现VideoPlayable

extension DiscoverSearchDynamicsListVideoCell: VideoPlayable{
    var viewToContainVideo: UIView{
        return contentView
    }
    
    var urlToPlay: URL? {
        return URL(string: getM.videoUrl)
    }
    
    func videoStatusChanged(changeTo isPlaying: Bool) {
        backIV.isHidden = isPlaying
    }
    
    func videoPlayTimeChanged(changeTo playTime: Float64) {
        getM.videoCurrentTime = playTime
    }
}

3.效果图 

代码请点击下载,感谢您的点赞​​​​​​​

原文地址:https://blog.csdn.net/weixin_38016552/article/details/127125663

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_24256.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注