Video Runs in View Controller - Swift
import AVFoundation
class WelcomeViewController: UIViewController {
var player: AVPlayer?
@IBOutlet var view_VideoPlayer: UIView!
override func viewWillAppear(_ animated: Bool) {
self.loadVideo()
self.player?.seek(to: kCMTimeZero)
self.player?.play()
}
private func loadVideo() {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
}
catch { }
let path = Bundle.main.path(forResource: "welcome_message", ofType:"mp4")
player = AVPlayer.init(url: NSURL(fileURLWithPath: path!) as URL) //(URL: NSURL(fileURLWithPath: path!) as URL)
DispatchQueue.main.async {
let playerLayer = AVPlayerLayer(player: self.player)
playerLayer.frame = CGRect(x: 0, y: 0, width: self.view_VideoPlayer.frame.width, height: self.view_VideoPlayer.frame.height)
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspect
playerLayer.zPosition = -1
NotificationCenter.default.removeObserver(self)
NotificationCenter.default.addObserver(self, selector: #selector(self.playerItemDidPlayToEndTime), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
self.view_VideoPlayer.layer.addSublayer(playerLayer)
}
}
@objc func playerItemDidPlayToEndTime() {
// load next video or something
NotificationCenter.default.removeObserver(self)
DispatchQueue.main.async {
self.player?.seek(to: kCMTimeZero)
self.player?.pause()
}
}
}
import AVFoundation
class WelcomeViewController: UIViewController {
var player: AVPlayer?
@IBOutlet var view_VideoPlayer: UIView!
override func viewWillAppear(_ animated: Bool) {
self.loadVideo()
self.player?.seek(to: kCMTimeZero)
self.player?.play()
}
private func loadVideo() {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
}
catch { }
let path = Bundle.main.path(forResource: "welcome_message", ofType:"mp4")
player = AVPlayer.init(url: NSURL(fileURLWithPath: path!) as URL) //(URL: NSURL(fileURLWithPath: path!) as URL)
DispatchQueue.main.async {
let playerLayer = AVPlayerLayer(player: self.player)
playerLayer.frame = CGRect(x: 0, y: 0, width: self.view_VideoPlayer.frame.width, height: self.view_VideoPlayer.frame.height)
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspect
playerLayer.zPosition = -1
NotificationCenter.default.removeObserver(self)
NotificationCenter.default.addObserver(self, selector: #selector(self.playerItemDidPlayToEndTime), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
self.view_VideoPlayer.layer.addSublayer(playerLayer)
}
}
@objc func playerItemDidPlayToEndTime() {
// load next video or something
NotificationCenter.default.removeObserver(self)
DispatchQueue.main.async {
self.player?.seek(to: kCMTimeZero)
self.player?.pause()
}
}
}
No comments:
Post a Comment