使用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.根据url资源创建一个播放器
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()
}
// 不加下面的方法,虽然可以放视频,可以听到声音
// 但是不能看到画面,得添加到相应的图层上去
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.创建播放器对象
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()
}
}
}