iOS swift 视频播放器控件Player

实现主要功能:
  • 1、返回前一页
  • 2、上下渐变层
  • 3、遮罩imageView层
  • 4、播放暂停按钮
  • 5、屏幕中间播放按钮
  • 6、进度条
  • 7、播放时间显示
  • 8、大屏/小屏切换
  • 9、屏幕亮度调节
  • 10、系统声音调节
  • 11、快进/快退
  • 12、点击屏幕隐藏/展示上下渐变层
github链接

https://github.com/kongzichixiangjiao/YYPlayer

使用实例:
 注:
 <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
     <plist version="1.0">
        <dict>
            <key>NSAllowsArbitraryLoads</key>
            <true/>
        </dict>
    </plist>

 // 示例:
    @IBOutlet weak var playerBackView: UIView!
 
    override func viewDidLoad() {
        super.viewDidLoad()
    }
 
    func initPlayerView() {
        self.pplayerBackView.addSubview(pView)

        playerBackView.addConstraint(NSLayoutConstraint(item: pView, attribute: .left, relatedBy: .equal, toItem: playerBackView, attribute: .left, multiplier: 1, constant: 0))
        playerBackView.addConstraint(NSLayoutConstraint(item: pView, attribute: .top, relatedBy: .equal, toItem: playerBackView, attribute: .top, multiplier: 1, constant: 0))
        playerBackView.addConstraint(NSLayoutConstraint(item: pView, attribute: .bottom, relatedBy: .equal, toItem: playerBackView, attribute: .bottom, multiplier: 1, constant: 0))
        playerBackView.addConstraint(NSLayoutConstraint(item: pView, attribute: .right, relatedBy: .equal, toItem: playerBackView, attribute: .right, multiplier: 1, constant: 0))
    }
 
    lazy var pView: YYPlayerView = {
        let v = YYPlayerView.loadPlayerView()
        v.urlString = "http://qiniu.puxinasset.com/099f507aed7c5799d5ff40386a1a9615.mp4"
        v.maskImageView.image = UIImage()
        return v
    }()

或者

        pView.snp.makeConstraints({ (make) in
            make.edges.equalTo(playerBackView)
        })
        let pView = YYPlayerView.loadPlayerView().then {
            $0.urlString = "http://qiniu.puxinasset.com/099f507aed7c5799d5ff40386a1a9615.mp4"
        }
添加系统类
import MediaPlayer
枚举
// MARK: 播放器状态枚举
enum YYPlayerState: Int {
    case play = 1, pause = 2, stop = 3, finished = 4, unknow = 99
}

// MARK: 播放器屏幕枚举
enum YYPlayerScreenState: Int {
    case full = 1, small = 2
}

YYPlayerView类中

主要设置如下参数即可

    // 是否展示预览图
    public var isShowMaskImageView: Bool = true
    // 快进/快退时间
    public var intervalTime: Double = 4
    // 播放的url
    public var urlString: String? {
        didSet {
            guard let url = URL(string: urlString!) else {
                print("错误 urlString ❎❌❌❌❌❎")
                return
            }
            
            config(url: url)
        }
    }

初始化方法

    // 初始化YYPlayerView方法
    static func loadPlayerView() -> YYPlayerView {
        return Bundle.main.loadNibNamed("YYPlayerView", owner: self, options: nil)?.last as! YYPlayerView
    }

更新视图:
1.初始化
2.横竖屏切换

    override func layoutSubviews() {
        super.layoutSubviews()
        // 横竖屏切换从新设置playerLayer大小, 第一次添加playerLayer也会走起
        screenView.layer.insertSublayer(YYPlayer.share.playerLayer, below: self.maskImageView.layer)
        YYPlayer.share.playerLayer.frame = bounds
    }

添加tap和pan手势
1.点击只操作隐藏/显示渐变层
2.pan主要操作亮度、快进/快退、声音

// 添加手势
    private func initGestureRecognizer() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapScreenView(_:)))
        self.screenView.addGestureRecognizer(tap)
        
        let pan = UIPanGestureRecognizer(target: self, action: #selector(panScreenView(_:)))
        self.screenView.addGestureRecognizer(pan)
    }

获取设置声音的slider来更改声音

    // 获取设置声音的slider
    lazy var volumeSlider: UISlider? = {
        let v = MPVolumeView()
        v.showsRouteButton = true
        v.showsVolumeSlider = true
        v.sizeToFit()
        v.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        for v in v.subviews {
            if (v.classForCoder.description() == "MPVolumeSlider") {
                return v as? UISlider
            }
        }
        return nil
    }()

实时更新进度条和时间的闭包

    // 实时更新进度条和时间的闭包
    lazy var displayLinkHandler: YYPlayer.DisplayLinkHandler = {
        [weak self] currentTime, catchTime, state in
        if let weakSelf = self {
            if state == .play {
                if !weakSelf.isSliderDragging {
                    weakSelf.currentTimeLabel.text = String(format: "%02d:%02d", Int(currentTime.seconds) / 60, Int(currentTime.seconds) % 60)
                    weakSelf.progressSlider.value = Float(currentTime.seconds / weakSelf.totalTime)
                    weakSelf.currentTime = currentTime.seconds
                }
            }
        }
    }

获取当前player的viewcontroller

// MARK: 获取当前的controller
extension YYPlayerView {
    
    fileprivate struct AssociatedKeys {
        static var playerViewController: UIViewController = UIViewController()
    }
    
    open var playerViewController: UIViewController? {
        get {
            guard let playerViewController = objc_getAssociatedObject(self, &AssociatedKeys.playerViewController) as? UIViewController else {
                var next = self.next
                while next != nil {
                    if next!.isKind(of: UIViewController.self) {
                        return next as? UIViewController
                    }
                    next = next?.next
                }
                return nil
            }
            return playerViewController
        }
    }
}

YYPlayer类

监听四中keyPath

    // 监听四种keyPath
    private let kPath_status = "status"
    private let kPath_loadedTimeRanges = "loadedTimeRanges"
    private let kPath_playbackBufferEmpty = "playbackBufferEmpty"
    private let kPath_playbackLikelyToKeepUp = "playbackLikelyToKeepUp"

单例

static let share: YYPlayer = YYPlayer()

添加通知:播放结束、异常中断、进入后台、进入前天

    // MARK: 监听通知:播放结束、异常中断、进入后台、进入前天
    fileprivate func addNotificationCenter() {
        // 添加视频播放结束通知
        NotificationCenter.default.addObserver(self, selector: #selector(didPlayToEndTimeNotification), name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
        
        // 添加视频异常中断通知
        NotificationCenter.default.addObserver(self, selector: #selector(playbackStalledNotification), name: Notification.Name.AVPlayerItemPlaybackStalled, object: playerItem)
        
        // 添加程序将要进入后台通知
        NotificationCenter.default.addObserver(self, selector: #selector(willEnterBcakgroundNotification), name: Notification.Name.UIApplicationWillResignActive, object: nil)
        
        // 添加程序已经返回前台通知
        NotificationCenter.default.addObserver(self, selector: #selector(didEnterPlayGroundNotification), name: Notification.Name.UIApplicationDidBecomeActive, object: nil)
    }

播放方法

    private func _play() {
        if playerInfoState != .readyToPlay {
            return
        }
        player.play()
        displayLink = CADisplayLink(target: self, selector: #selector(refreshProgress))
        displayLink.add(to: RunLoop.main, forMode: .defaultRunLoopMode)
    }
    // 实时刷新progress
    @objc private func refreshProgress() {
        displayLinkHandler(playerItem.currentTime(), CMTime(), .play)
    }

YYPlayerButton类

class YYPlayerButton: UIButton {
    
    var playState: YYPlayerState! {
        didSet {
            switch playState {
            case .play:
                self.isSelected = true
            case .pause:
                self.isSelected = false
            case .unknow:
                print("更改状态时候发生未知错误")
            case .none:
                break
            case .some(_):
                break
            }
        }
    }
    
    var fullState: YYPlayerScreenState! {
        didSet {
            switch fullState {
            case .full:
                self.isSelected = true
            case .small:
                self.isSelected = false
            case .none:
                break
            case .some(_):
                break
            }
        }
    }
}

YYPlayerGradualChangeView类

class YYPlayerGradualChangeView: UIView {
    
    @IBInspectable var isUpDeep: Bool = false
    
    var gradientLayer: CAGradientLayer?
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.backgroundColor = UIColor.clear
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let gradientLayer = initGradientLayer()
        self.layer.addSublayer(gradientLayer)
        gradientLayer.frame = self.layer.bounds
    }
    
    func initGradientLayer() -> CAGradientLayer {
        if let g = gradientLayer {
            return g
        }
        let g = CAGradientLayer()
        let colors = [
            UIColor(red: 0, green: 0, blue: 0, alpha: 0.8).cgColor,
            UIColor(red: 0, green: 0, blue: 0, alpha: 0.1).cgColor,
            ]
        let locations = [
            0.0, 1
        ]
        g.colors = colors
        g.locations = locations as [NSNumber]
        let startPoint = self.isUpDeep ? CGPoint(x: 0.5, y: 0) : CGPoint(x: 0.5, y: 1)
        let endPoint = self.isUpDeep ? CGPoint(x: 0.5, y: 1) : CGPoint(x: 0.5, y: 0)
        g.startPoint = startPoint
        g.endPoint = endPoint
        
        gradientLayer = g
        
        return g
    }
}

设置屏幕旋转

var extension_key: UInt = 1205
extension UIResponder {
    
    var allowRotation: Bool? {
        get {
            return objc_getAssociatedObject(self, &extension_key) as? Bool
        }
        set(newValue) {
            objc_setAssociatedObject(self, &extension_key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    // UIDevice.current.setValue(value, forKey: kOrientation) 之后调用此方法
    @objc(application:supportedInterfaceOrientationsForWindow:) func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        if allowRotation == true {
            return .landscapeRight
        } else {
            return .portrait
        }
    }
}

详细代码点击链接
https://github.com/kongzichixiangjiao/YYPlayer

感谢:ly_coder
https://github.com/LY-Coder/LYPlayer

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,542评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,596评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,021评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,682评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,792评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,985评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,107评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,845评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,299评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,612评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,747评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,441评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,072评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,828评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,069评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,545评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,658评论 2 350

推荐阅读更多精彩内容