当AVPlayer进入后台时,切换到仅音频的HLS格式副本



假设我在AVPlayer中有一个HLS视频,我希望在应用程序后台时继续播放音频。

是的,我用这个做到了:

  1. 将背景模式:音频功能添加到应用程序中,以授予我的应用程序执行此操作的权限。此处描述
  2. 在AppDelegate中等待applicationDidEnterBackground并在AVPlayerViewController&保存对玩家的引用
  3. 在AppDelegate中等待applicationWillEnterForeground并设置此处描述的player = savedPlayerReference

现在,得到这个。假设我的HLS主清单有几个视频+音频格式副本,然后是一个仅音频曲目的格式副本。理想情况下,当AVPlayer转到后台并停止播放视频时,我希望AVPlayer使用主清单中的仅音频曲目(以节省带宽,而不是使应用程序对音频/视频曲目进行解复用并解码未显示的视频(。

我该怎么做?我认为它可能会自动这样做,但从检查网络流量来看,当应用程序处于后台时,AVPlayer似乎停留在最后一个格式副本上,并且从未切换到仅音频格式副本清单

我找到了答案,感觉有点像黑客,但它正在发挥作用。

解决方案是,在断开连接之前,要访问底层AVPlayerItem实例,并将preferredPeakBitRate设置为音频格式副本(例如300000(所需的级别

类似这样的东西:

func applicationDidEnterBackground(_ application: UIApplication) {
// set preferred bitrate to the bitrate we expect from the audio rendition
playerViewController.player?.currentItem?.preferredPeakBitRate = 300000
savedPlayer = playerViewController.player
// disconnect AVPlayer from the presentation
playerViewController.player = nil;
}

然后,当应用程序返回前台时,将preferredPeakBitRate重新设置为0,以便视频轨道返回

func applicationWillEnterForeground(_ application: UIApplication) {
// unset our preferredPeakBitRate value
playerViewController.player?.currentItem?.preferredPeakBitRate = 0
// re-connect AVPlayer to the presentation
playerViewController.player = savedPlayer;
}

我应该注意到,在其他情况下(比如创建质量选择器或试图对特定的视频格式进行更多控制(,我没有看到preferredPeakBitRate可靠地工作。

最新更新