swift for ios 視訊播放
swift視訊播放一般常用的方式有兩種 AVPlayer 和MPMoviePlayer
這些方法直接繫結一個viewController不需要任何控制元件就可以用 非常方便
程式碼
方式一(推薦用,功能比較靈活)
import UIKit
import AVFoundation
import AVKit
class T_PlayerViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://www.zghkt.cn/t_tmp.php?tid=23&url=http://file.zghkt.cn/hua_xu_cheng_pian_.mp4"
let player = AVPlayer(URL: url!)
let playerController = AVPlayerViewController()
playerController.player = player
self.addChildViewController(playerController)
self.view.addSubview(playerController.view)
playerController.view.frame = self.view.frame
player.play()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
第二種方法(已過時)
import UIKit
import MediaPlayer
class T_PlayerViewController: UIViewController {
var moviePlayer:MPMoviePlayerController?
override func viewDidLoad() {
super.viewDidLoad()
// //定義一個視訊檔案路徑
// let filePath = NSBundle.mainBundle().pathForResource("sample130", ofType: "mp4")
// //定義一個視訊播放器,通過本地檔案路徑初始化
// moviePlayer = MPMoviePlayerController(contentURL: NSURL(fileURLWithPath: filePath!))
//播放線上視訊
moviePlayer = MPMoviePlayerController(contentURL: NSURL(string: "http://www.zghkt.cn/t_tmp.php?tid=23&url=http://file.zghkt.cn/hua_xu_cheng_pian_.mp4"))
//設定播放器樣式 - 沒有done
moviePlayer!.controlStyle = MPMovieControlStyle.Embedded
//設定大小和位置
moviePlayer?.view.frame = self.view.frame
//新增到介面上
self.view.addSubview(moviePlayer!.view)
//開始播放
moviePlayer?.play()
}
override funcdidReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}