【问题标题】:How do I pause and play background video when navigating from foreground to background?从前台导航到后台时如何暂停和播放背景视频?
【发布时间】:2016-05-13 17:42:13
【问题描述】:

当我启动我的应用程序时,我正在播放背景视频。如果我碰巧按下主页按钮,我希望视频暂停并从中断的地方继续。这是我的代码:

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。或者对我来说有点太混乱了。

【问题讨论】:

    标签: swift avplayerviewcontroller


    【解决方案1】:

    您应该能够通过 NSNotificationCenter 注册后台/前台通知来播放或暂停您的 aPlayer,如下所示:

    let notificationCenter = NSNotificationCenter.defaultCenter()
        notificationCenter.addObserver(self, selector: #selector(pauseVideoForBackgrounding), name: UIApplicationDidEnterBackgroundNotification, object: nil)
    

    有几个可用的 UIApplication 通知名称,包括 UIApplicationWillEnterForegroundNotification。您可以根据需要利用尽可能多的通知,让您的视频播放器类知道应用状态发生了什么。

    如果您支持 iOS 8 或更低版本,请确保从您添加到视图控制器的任何 NSNotifications 中删除作为观察者的播放器类。

    【讨论】:

    • 甜蜜!很高兴这有效!如果它对你有用,你介意接受答案还是赞成它?谢谢
    • 很抱歉,这是新的。已检查,但不幸的是,我没有足够的积分来投票。谢谢,一旦我投票,我会投票!
    【解决方案2】:

    是的,所有特定于应用程序的操作都发生在您的 appdelegate 协议中。将暂停代码放在 appdelegate 的 applicationDidEnterBackground 函数中,将恢复代码放在 applicationWillEnterForeground 中。

    I would check out Apple's docs on the AppDelegate protocol,尤其是这两个函数,因为在您的应用程序变为非活动状态之前,您完成任务所需的时间还需要考虑更多(尽管如果您只是暂停并恢复 AVPlayer 你应该没问题)。

    【讨论】:

      猜你喜欢
      • 2018-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-22
      • 2015-10-27
      • 1970-01-01
      • 2015-06-18
      • 1970-01-01
      相关资源
      最近更新 更多