AVPlayerViewController is a subclass of UIViewController. So instead of using a regular view controller create your custom movie player controller as follow:
Do not subclass AVPlayerViewController. Overriding this class’s
methods is unsupported and results in undefined behavior.
Try like this:
import UIKit
import AVKit
import AVFoundation
class MoviePlayerViewController: AVPlayerViewController {
override func viewDidLoad() {
super.viewDidLoad()
player = AVPlayer(URL: url)
videoGravity = AVLayerVideoGravityResizeAspect
showsPlaybackControls = true
// player?.play() // uncomment this line to autoplay
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didPlayToEndTime", name: AVPlayerItemDidPlayToEndTimeNotification, object: nil)
}
func didPlayToEndTime(){
print("didPlayToEndTime")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
To use it as a background you can do as follow:
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
let moviePlayerController = AVPlayerViewController()
var aPlayer = AVPlayer()
func playBackgroundMovie(){
if let url = NSBundle.mainBundle().URLForResource("video", withExtension: "mov") {
aPlayer = AVPlayer(URL: url)
}
moviePlayerController.player = aPlayer
moviePlayerController.view.frame = view.frame
moviePlayerController.view.sizeToFit()
moviePlayerController.videoGravity = AVLayerVideoGravityResizeAspect
moviePlayerController.showsPlaybackControls = false
aPlayer.play()
view.insertSubview(moviePlayerController.view, atIndex: 0)
}
func didPlayToEndTime(){
aPlayer.seekToTime(CMTimeMakeWithSeconds(0, 1))
aPlayer.play()
}
override func viewDidLoad() {
super.viewDidLoad()
playBackgroundMovie()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didPlayToEndTime", name: AVPlayerItemDidPlayToEndTimeNotification, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…