我已经在iOS 8中实现了在后台播放电影的功能,现在当我想在iOS 9中使用它时,它会向我发出警告,并说最好不要使用MPMoviePlayer而是使用AVPlayer。但是我对AVPlayer一无所知。如何在不使用AVPlayer而不是MPMoviePlayer的警告的情况下将其转换为适当的函数?继承人的功能:
func playVideo() ->Bool { let path = NSBundle.mainBundle().pathForResource("video", ofType:"mov") //take path of video let url = NSURL.fileURLWithPath(path!) moviePlayer = MPMoviePlayerController(contentURL: url) //asigning video to moviePlayer if let player = moviePlayer { player.view.frame = self.view.bounds //setting the video size to the view size player.controlStyle = MPMovieControlStyle.None //Hiding the Player controls player.prepareToPlay() //Playing the video player.repeatMode = .One //Repeating the video player.scalingMode = .AspectFill //setting the aspect ratio of the player self.view.addSubview(player.view) self.view.addSubview(blurView) self.view.sendSubviewToBack(blurView) self.view.sendSubviewToBack(player.view) //adding the player view to viewcontroller return true } return false }
AVPlayerViewController是UIViewController的子类。因此,不要使用常规的视图控制器,而是按照以下步骤创建自定义电影播放器控制器:
不要将AVPlayerViewController子类化。不支持覆盖此类的方法,并导致未定义的行为。
尝试这样:
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. } }
要将其用作背景,可以执行以下操作:
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. } }