今天要分享的是,如何用 AVPlayerViewController 顯示影片
成品:
{%youtube wCKodbvifQM %}
快速介紹 AVFoundation、AVKit:
AVFoundation:
處理基於時間的視聽媒體。
可以輕鬆播放、創建和編輯 QuickTime 電影和 MPEG-4 文件,支援 HLS ( HTTP Live Streaming 媒體傳輸協議 ),並在應用程序中構建強大的媒體功能。
AVKit:
基於 AVFoundation 框架,提供播放影片內容的介面、建立媒體播放服務。
主要包含 AVPictureInPictureController、AVPlayViewController
在 project 加入影片檔
從 storyboard 設計畫面
由於 AVPlayerViewController 來自 AVKit,因此必須import AVKit
此外 AVKit 基於 AVFoundation 框架,因此必須import AVFoundation
在 @IBAction 設定 AVPlayerViewController 的播放影片,因為有三個 Button ,因此用 switch 判斷按到哪一個 Button 。
@IBAction func didTapButton (btn: UIButton){
switch btn {
case btn1:
let player1 = AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "151", ofType: "mov")!))
let vc1 = AVPlayerViewController()
vc1.player = player1
present(vc1, animated: true)
case btn2:
let player2 = AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "152", ofType: "mov")!))
let vc2 = AVPlayerViewController()
vc2.player = player2
present(vc2, animated: true)
default:
let player3 = AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "swag", ofType: "mov")!))
let vc3 = AVPlayerViewController()
vc3.player = player3
present(vc3, animated: true)
}
}
forResource: "影片名稱"
ofType: "檔案格式"
附上完整程式碼
import UIKit
import AVKit
import AVFoundation
class MainVC: UIViewController {
@IBOutlet weak var btn1: UIButton!
@IBOutlet weak var btn2: UIButton!
@IBOutlet weak var btn3: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true, animated: false) // 隱藏指示條
}
@IBAction func didTapButton (btn: UIButton){
switch btn {
case btn1:
let player1 = AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "151", ofType: "mov")!))
let vc1 = AVPlayerViewController()
vc1.player = player1
present(vc1, animated: true)
case btn2:
let player2 = AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "152", ofType: "mov")!))
let vc2 = AVPlayerViewController()
vc2.player = player2
present(vc2, animated: true)
default:
let player3 = AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "swag", ofType: "mov")!))
let vc3 = AVPlayerViewController()
vc3.player = player3
present(vc3, animated: true)
}
}
}
這樣就完成顯示影片啦!明天會分享新的實作,敬請期待!