AVPlayerViewController播放視頻分兩種形式
- 內(nèi)嵌視圖的形式顯示
- 模態(tài)視圖的形式顯示
一.初始化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
}
二.內(nèi)嵌視圖的形式顯示
@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()
}
效果圖如下:
點擊AVPlayerViewController
可以全屏播放
三.模態(tài)視圖的形式顯示
@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()
}
}
效果圖如下:
四.停止視頻播放
@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
}