iOS 启用 AVPlayer 在后台继续播放

iOS Enable AVPlayer to continue playing in background

我正在开发一个带有内置视频播放器的应用程序,可以播放 mp4 磁盘中的视频,我正在努力让它 继续 播放音频(视频的)当 app 进入后台时

我已经阅读了许多其他堆栈溢出问题,但 none 的答案适用于我的情况。

我已添加:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
      print("AVAudioSession Category Playback OK")

    do {
      try AVAudioSession.sharedInstance().setActive(true)
      print("AVAudioSession is Active")
    } catch let error as NSError {
      print(error.localizedDescription)
    }
  } catch let error as NSError {
      print(error.localizedDescription)
  }
}

此外,我在应用程序的 Info.plist 文件中也有所需的后台模式密钥 App plays audio or streams audio/video using AirPlay。 但是,AVPlayer 会在应用程序进入后台时停止。

有人知道该应用可能有什么问题吗?

谢谢:)

编辑: 注意:我将 AVPlayerLayerAVPlayer 一起使用。也许这就是问题所在?

AVPlayerLayer 可能会产生问题。您需要将其从 AVPlayer 对象中删除。在应用程序进入后台之前设置为 nil

根据Apple Document解决的两种方法,

  1. Disable the video tracks in the player item (file-based content only).

  2. Remove the AVPlayerLayer from its associated AVPlayer (set the AVPlayerLayer player property to nil).

请参阅此 link 了解更多信息。

首先您必须在功能中启用“背景音频”。请按照以下 link 进行操作。

[See image to Enable Background Audio]

当您的应用移至后台时,将您的播放器分配给 nil。

// If presenting video with AVPlayerViewController
    playerViewController.player = nil

// If presenting video with AVPlayerLayer
    playerLayer.player = nil

当您的应用程序再次移至前台时,请按照以下说明进行操作。

// If presenting video with AVPlayerViewController
playerViewController.player = player

// If presenting video with AVPlayerLayer
playerLayer.player = player