CALayer解析4:AVPlayerLayer

1.简介

AVPlayerLayer是AVFoundation的底层图层。拥有AVPlayer属性,可以播放媒体文件。

2.属性

属性 作用
player 播放器属性,拥有更多的属性和方法,可以控制视频的播放等,比如rate,播放速率,0表示暂停,同pause()效果
videoGravity 设置视频显示的绘制方式
isReadyForDisplay 检查视频是否准备好显示
videoRect 视频在layer内的播放位置
pixelBufferAttributes 像素缓冲区内的数据

3.使用

//需要先导入AVFoundation
import AVFoundation
class ViewController: UIViewController {
    
    var player: AVPlayer!
    var playBtn: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        setUpLayer()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


    func setUpLayer() {
        playBtn = UIButton(frame: CGRect(x: 0, y: view.frame.height-30, width: view.frame.width, height: 30))
        playBtn.setTitle("Play", for: .normal)
        playBtn.setTitleColor(.black, for: .normal)
        playBtn.addTarget(self, action: #selector(playButtonTap(btn:)), for: .touchUpInside)
        view.addSubview(playBtn)
        
        //创建出layer实例
        let playerLayer = AVPlayerLayer()
        playerLayer.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height-30)
        
        //设置播放器
        let url = Bundle.main.url(forResource: "Video", withExtension: "m4v")
        player = AVPlayer(url: url!)
        
        //播放器设置
        player.actionAtItemEnd = .none
        playerLayer.player = player
        view.layer.addSublayer(playerLayer)
        
        //添加视频播放完毕后的通知的监听
        NotificationCenter.default.addObserver(self, selector: #selector(playerDidReachEndNotificationHandler(notification:)), name: NSNotification.Name(rawValue: "AVPlayerItemDidPlayToEndTimeNotification"), object: player.currentItem)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    //播放按钮
    func playButtonTap(btn: UIButton) {
        if btn.titleLabel?.text == "Play" {
            player.play()
            btn.setTitle("Pause", for: .normal)
        }else {
            player.pause()
            btn.setTitle("Play", for: .normal)
        }
    }
    
    //重新播放
    func playerDidReachEndNotificationHandler(notification: Notification) {
        let playerItem = notification.object as! AVPlayerItem
        playerItem.seek(to: kCMTimeZero)
    }
    
}

效果如图

CALayer解析4:AVPlayerLayer_第1张图片
屏幕快照 2017-08-30 上午11.13.12.png

你可能感兴趣的:(CALayer解析4:AVPlayerLayer)