1. 程式人生 > >[Swift通天遁地]八、媒體與動畫-(2)實現視頻文件的播放和畫中畫

[Swift通天遁地]八、媒體與動畫-(2)實現視頻文件的播放和畫中畫

splay 滾動 path 轉換 添加 seek 模擬器 cati aud

本文將演示使用AVPlayerViewController播放視頻並實現畫中畫。

往項目中導入了一個視頻文件。

在左側的項目導航區,打開視圖控制器的代碼文件【ViewController.swift】

 1 import UIKit
 2 //在當前的類文件中,
 3 //引入需要用到的相關類庫
 4 import AVFoundation
 5 import AVKit
 6 
 7 class ViewController: UIViewController, AVPlayerViewControllerDelegate {
 8     
 9     var playerVC : AVPlayerViewController!
10
override func viewDidLoad() { 11 super.viewDidLoad() 12 // Do any additional setup after loading the view, typically from a nib. 13 14 //獲得視頻文件在項目中的路徑。 15 let moviePath = Bundle.main.path(forResource: "Sunrise", ofType: "mp4") 16 //將視頻路徑轉換成網址對象。 17
let movieURL = URL(fileURLWithPath: moviePath!) 18 //初始化一個視頻播放器,播放指定的視頻文件 19 let avPlayer = AVPlayer(url: movieURL as URL) 20 21 //let view = UIView(frame: CGRect(x: 20, y: 180, width: 100, height: 100)) 22 //view.backgroundColor = .orange 23 //self.view.addSubview(view)
24 25 //初始化一個視頻播放控制器 26 playerVC = AVPlayerViewController() 27 //設置控制器對象的播放屬性 28 playerVC.player = avPlayer 29 //保持視頻的寬高比,並使播放內容自動適應播放窗口的大小 30 playerVC.videoGravity = AVLayerVideoGravity.resizeAspect 31 //設置在特定的設備上,允許畫中畫模式 32 playerVC.allowsPictureInPicturePlayback = true 33 //在視頻播放時,顯示播放控制功能區 34 playerVC.showsPlaybackControls = true 35 //設置播放器的顯示區域,保持和根視圖的顯示區域相同 36 playerVC.view.frame = self.view.bounds 37 //設置播放器的代理對象為本身 38 playerVC.delegate = self 39 40 //通過調用播放器的播放方法,開始播放視頻文件。 41 playerVC.player!.play() 42 //self.view.insertSubview(playerVC.view, belowSubview: view) 43 //將視圖播放器視圖,添加到根視圖中 44 self.view.addSubview(playerVC.view) 45 46 NotificationCenter.default.addObserver(self, selector: #selector(ViewController.playEnd(notification:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil) 47 } 48 49 func playerViewControllerDidStartPictureInPicture(_ playerViewController: AVPlayerViewController) { 50 print("playerViewControllerDidStartPictureInPicture") 51 } 52 53 @objc func playEnd(notification: Notification) 54 { 55 print("playEnd") 56 print(playerVC.player?.currentTime() as Any) 57 playerVC.player?.seek(to: CMTime(seconds: 1.0, preferredTimescale: CMTimeScale(NSEC_PER_SEC))) 58 playerVC.player!.play() 59 } 60 61 override func didReceiveMemoryWarning() { 62 super.didReceiveMemoryWarning() 63 // Dispose of any resources that can be recreated. 64 } 65 }

點擊項目名稱【DemoApp】,進入項目屬性設置面板

點擊【Capabilities】能力標簽,進入項目功能開啟面板。

點擊右側的垂直滾動條,點擊【Background Modes】設置為【ON】

勾選【Audio、AirPlay、and Picture in Picture】激活視頻播放的畫中畫模式。

模擬器啟動後,開始播放項目中的視頻文件,點擊工具條右側的畫中畫圖標,切換至畫中畫模式。

進入畫中畫模式後,視頻在屏幕中的一個浮動窗口中進行播放。

[Swift通天遁地]八、媒體與動畫-(2)實現視頻文件的播放和畫中畫