【发布时间】:2017-07-13 11:20:25
【问题描述】:
我使用AVPlayerViewController 在我的应用中播放短视频。
如果在用户在我的应用中播放视频之前有应用在后台播放音频,我希望在我的视频播放器关闭后恢复其他应用的背景音频播放。我目前使用AVAudioSession.setActive(false, with: .notifyOthersOnDeactivation) 来做到这一点。
即使 Apple 的音乐应用程序和 Podcasts 应用程序在我拨打 AVAudioSession.setActive(false, with: .notifyOthersOnDeactivation) 后确实恢复播放——没有呼叫就不会恢复,因此这意味着此呼叫确实有效——我测试的第 3 方音乐或播客应用程序都没有( Spotify、SoundCloud、亚马逊音乐、阴天)。
这是我的代码:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// I know it's not the best place to call setActive nor it covers all the cases. It's just a convenient place to put the code to test its effect after dismissing the video player.
do {
try AVAudioSession.sharedInstance().setActive(false, with: .notifyOthersOnDeactivation)
} catch {
print(error)
}
}
@IBAction func play(_ sender: Any) {
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print(error)
}
let playerController = AVPlayerViewController()
playerController.player = AVPlayer(url: URL(string: "http://gslb.miaopai.com/stream/UkjiD45ddxZFQ79I2bLaGg__.mp4")!)
playerController.player?.play()
present(playerController, animated: true)
}
起初我认为这可能是这些 3rd 方应用程序的错。但后来我用官方推特应用测试了它们,发现它们可以在推特应用中播放视频后恢复音频播放。
那么我错过了什么?我应该怎么做才能让这些第 3 方应用在我的应用中播放视频后恢复音频播放,就像 Twitter 应用一样?
PS:这里有完整的project,有兴趣的可以试试。
【问题讨论】:
标签: ios audio avfoundation avplayerviewcontroller avkit