【问题标题】:Switch to audio-only HLS rendition when AVPlayer goes into the background当 AVPlayer 进入后台时切换到纯音频 HLS 再现
【发布时间】:2021-07-01 19:27:15
【问题描述】:
假设我在 AVPlayer 中有一个 HLS 视频,我希望音频在应用程序进入后台时继续播放。
是的,我能够做到这一点:
- 将背景模式:音频功能添加到应用程序以授予我的应用程序执行此操作的权限。 Described here
- 在 AppDelegate 中等待 applicationDidEnterBackground 并在 AVPlayerViewController 上设置 player = nil 并保存对播放器的引用
- 在 AppDelegate 中等待 applicationWillEnterForeground 并设置
player = savedPlayerReference Described here
现在,得到这个。假设我的 HLS 主清单有一些视频 + 音频再现,然后是一个只有音频轨道的再现。理想情况下,当 AVPlayer 进入后台并停止播放视频时,我希望 AVPlayer 使用主清单中的纯音频轨道(为了节省带宽,而不是让应用程序对音频/视频轨道进行解复用并解码视频未显示)。
我该怎么做?我认为它可能会自动以这种方式运行,但是从检查网络流量来看,当应用程序处于后台时,AVPlayer 会停留在最后一个再现上,并且它永远不会切换到纯音频再现清单
【问题讨论】:
标签:
ios
video-streaming
avplayer
http-live-streaming
【解决方案1】:
我想出了答案,感觉有点像 hack,但它确实有效。
解决方案是在断开连接之前访问底层 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 可靠地工作。