iOS视频播放AVPlayerViewController

AVPlayerViewController播放视频分两种形式

  • 内嵌视图的形式显示
  • 模态视图的形式显示

一.初始化AVPlayerViewController


 func loadPlayer() -> Void {
        guard let movieUrl = Bundle.main.path(forResource: "zh-zhfanti-en", ofType: "m4v") else {
            return
        }
        
        let player = AVPlayer(url: URL(fileURLWithPath: movieUrl))
        playerViewController = AVPlayerViewController()
        playerViewController!.player = player
    }
    

二.内嵌视图的形式显示


 @IBAction func handlePlayInViewEvent(sender: AnyObject) {
        loadPlayer()
        
        guard (playerViewController != nil) else {
            return
        }
        
        containerView?.addSubview(playerViewController!.view)
        playerViewController?.view.frame = containerView!.bounds
        self.addChild(playerViewController!)
        playerViewController?.player?.play()
   }
   

效果图如下:


inview_overview.png

点击AVPlayerViewController可以全屏播放

三.模态视图的形式显示

    @IBAction func handlePlayWithModelViewEvent(sender: AnyObject) {
        
        loadPlayer()
        
        guard (playerViewController != nil) else {
            return
        }
        
        
        self.present(playerViewController!, animated: true) { [weak self] () -> Void in
            guard let self = self else {
                return
            }
            self.playerViewController?.player?.play()
        }
    }


效果图如下:

modelview_overview.png

四.停止视频播放


 @IBAction func handleStopPlayEvent(sender: AnyObject? ){
        
        guard playerViewController != nil else {
            return
        }
        
        if ((playerViewController?.parent) != nil) {
            playerViewController?.view.removeFromSuperview()
            playerViewController?.removeFromParent()
        } else if playerViewController != nil && playerViewController!.isModalInPresentation {
            playerViewController?.dismiss(animated: (sender != nil ? true:false), completion: nil)
        }
        
        playerViewController?.player?.pause()
        playerViewController = nil
  }
    

你可能感兴趣的:(iOS视频播放AVPlayerViewController)