【问题标题】:Swift handling wake from sleep and resuming play?快速处理从睡眠中唤醒并恢复游戏?
【发布时间】:2016-11-01 01:37:03
【问题描述】:

我在 tvOS 上有一个使用 AVPlayerViewController 播放流式音频的应用程序。这工作正常,即使在后台运行。问题是,当 AppleTV 进入睡眠状态并且何时醒来时,播放器被卡住,只有强制退出应用程序才能让我再次开始播放。

我的应用程序是否应该处理某个事件才能正常恢复播放?我应该在文档中寻找什么?

基本代码是:

override func viewDidLoad() {
    super.viewDidLoad()

    // loading details fron plist
    if let stationInfo = readStationSettings() {
        stationUrl = stationInfo["url"] as? String
        stationName = stationInfo["name"] as? String
        stationDescription = stationInfo["description"] as? String
        stationImage = stationInfo["image"] as? UIImage
    } else {
        trackTitle = "Unable to find station details"
        return
    }

    let videoURL = URL(string: stationUrl!)

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true, with: .notifyOthersOnDeactivation)
    } catch let error as NSError {
        print(error.localizedDescription)
    }

    playerItem = AVPlayerItem(url: videoURL!)

    self.player=AVPlayer(playerItem: playerItem!)

    playerLayer=AVPlayerLayer(player: player)

    self.player?.play()
}

【问题讨论】:

  • 是的,请添加一些代码。
  • @RomanPodymov 我已经更新了问题

标签: swift swift3 tvos apple-tv avplayerviewcontroller


【解决方案1】:

我在使用 iOS iPhone 应用时遇到了同样的问题,我认为该解决方案可能会对您有所帮助。我正在使用AVPlayerViewController 在推送视图控制器中呈现视频。当视频全屏播放并且应用程序进入睡眠状态时,除非您退出应用程序,否则视频将永远无法恢复播放。所以这实际上是你遇到的同样的问题。

不幸的是,解决方案涉及在AVPlayerViewController 上调用一个私有函数,因为没有其他方法可以以我所知道的任何其他方式退出全屏模式。我的 AppDelegate 持有一个播放器视图控制器的实例,当 App 退出活动模式时,将调用以下代码:

let appDelegate = UIApplication.getAppDelegate()
if let player = appDelegate.playerController.player {
    if let cl = NSClassFromString("AVFullScreenViewController") {
        for window in UIApplication.sharedApplication().windows {
            if let pvc = window.rootViewController?.presentedViewController {
                if pvc.isKindOfClass(cl) {
                    let dSel = NSSelectorFromString("exitFullScreenAnimated:completionHandler:")
                    if appDelegate.playerController.respondsToSelector(dSel) {
                        appDelegate.playerController.performSelector(dSel, withObject: false, withObject: nil)
                    }
                    break
                }
            }
        }
    }

    player.pause()
    appDelegate.playerController.player = nil
    appDelegate.playerController.removeFromParentViewController()
    appDelegate.playerController.navigationController?.popViewControllerAnimated(false)
}

此代码在 Swift 2.3 中运行,因此您可能需要将其应用于其他 Swift 或 Objective C 版本。 请注意,这涉及调用私有 API 调用,这是一项有风险的业务。 无论如何,我希望这会有所帮助。

另请参阅 Apple 开发者论坛上的 this thread

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 2012-10-08
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 2014-07-29
    相关资源
    最近更新 更多