使用AVPlayer 播放遠程視頻
ViewController.swift
import UIKit
import AVFoundation
class ViewController: UIViewController {
// 成員變量
var player : AVPlayer?
// MARK: 懶加載
private lazy var layer : AVPlayerLayer = {
// 獲取遠程視頻資源
// 0.獲取遠程視頻url
let remoteURL = NSURL(string: "http://v1.mukewang.com/57de8272-38a2-4cae-b734-ac55ab528aa8/L.mp4")
// 1.根據(jù)url資源創(chuàng)建一個播放器
self.player = AVPlayer(URL: remoteURL!)
let layer = AVPlayerLayer(player: self.player)
return layer
}()
override func viewDidLoad() {
super.viewDidLoad()
view.layer .addSublayer(self.layer)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
player?.play()
}
// 不加下面的方法,雖然可以放視頻,可以聽到聲音
// 但是不能看到畫面,得添加到相應(yīng)的圖層上去
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
layer.frame = view.bounds
}
}
使用MPMoviePlayerController播放視頻
ViewController.swift
import UIKit
import MediaPlayer
class ViewController: UIViewController {
/** 播放器*/
var pc : MPMoviePlayerController?
override func viewDidLoad() {
super.viewDidLoad()
// 0.獲取資源路徑
let remoteURL = NSURL(string: "http://v1.mukewang.com/57de8272-38a2-4cae-b734-ac55ab528aa8/L.mp4")
// 1.創(chuàng)建播放器對象
pc = MPMoviePlayerController(contentURL: remoteURL)
view .addSubview((pc?.view)!)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
pc?.play()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
pc?.view.frame = view.bounds
}
}
使用MPMoviePlayerViewController播放視頻
ViewController.swift
import UIKit
import MediaPlayer
class ViewController: UIViewController {
/** 播放器 */
var pvc : MPMoviePlayerViewController?
override func viewDidLoad() {
super.viewDidLoad()
// 0.獲取遠程視頻url
let remoteURL = NSURL(string: "http://v1.mukewang.com/57de8272-38a2-4cae-b734-ac55ab528aa8/L.mp4")
pvc = MPMoviePlayerViewController(contentURL: remoteURL)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if (presentedViewController != nil) {
return ;
}
presentViewController(pvc!, animated: true) { () -> Void in
self.pvc?.moviePlayer.play()
}
}
}
iOS9.0之后, 需要使用AVPlayerViewController
ViewController.swift
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
/** 播放器 */
var playerVC: AVPlayerViewController?
override func viewDidLoad() {
super.viewDidLoad()
playerVC = AVPlayerViewController()
// 0.獲取遠程視頻url
let remoteURL = NSURL(string: "http://v1.mukewang.com/57de8272-38a2-4cae-b734-ac55ab528aa8/L.mp4")
let player = AVPlayer(URL: remoteURL!)
playerVC?.player = player
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if (presentedViewController != nil) {
return ;
}
presentViewController(playerVC!, animated: true) { () -> Void in
self.playerVC?.player?.play()
}
}
}