从前景导航到背景时,如何暂停播放背景视频?
我有一个背景视频,当我开始我的应用程序播放。我想要视频暂停并恢复它停止的位置,如果我碰巧碰到了主屏幕按钮。这里是我的代码:从前景导航到背景时,如何暂停播放背景视频?
class ViewController: UIViewController
{
let moviePlayerController = AVPlayerViewController()
var aPlayer = AVPlayer()
func playBackgroundMovie()
{
if let url = NSBundle.mainBundle().URLForResource("IMG_0489", withExtension: "m4v")
{
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()
{
// Do any additional setup after loading the view, typically from a nib.
super.viewDidLoad()
playBackgroundMovie()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.didPlayToEndTime), name: AVPlayerItemDidPlayToEndTimeNotification, object: nil)
}
我是否必须在应用程序委托中执行一些操作?我查看了以前的视频,但我认为其中一些正在使用过时的swift版本。或者对我来说有点太混乱。
您应该能够为backgrounding注册/通过NSNotificationCenter前景化通知播放或暂停aPlayer像这样:
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: #selector(pauseVideoForBackgrounding), name: UIApplicationDidEnterBackgroundNotification, object: nil)
有包括UIApplicationWillEnterForegroundNotification几个可用的UIApplication的通知名字。您可以根据需要利用尽可能多的通知,让您的视频播放器课程知道应用状态正在发生什么。
如果您支持iOS 8或更低版本,请确保从添加到视图控制器的任何NSNotifications中以观察者身份移除播放器类。
是的,所有应用程序特定的操作都发生在您的appdelegate协议中。请将您的暂停代码放入您的appdelegate的applicationDidEnterBackground
函数中,并将您的简历代码放入applicationWillEnterForeground
。
I would check out Apple's docs on the AppDelegate
protocol,尤其是这两个函数,因为在您的应用程序变为不活动状态之前需要花费更多的时间来完成任务(尽管如果您只是暂停和恢复一个AVPlayer
你应该没问题)。
谢谢你! –
非常感谢!工作! –
甜!很高兴工作!你介意接受答案,如果它为你工作或upvoting它?谢谢 –
对不起,新的这一点。检查,但我没有足够的积分投票不幸的。谢谢,我会投票,一旦我做! –