我遇到了在后台观察输出音量的问题,显然是因为当应用输入后台时音频会话变为非活动状态。我已经在项目设置中打开音频的后台模式,它没有帮助。
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let audioSession = AVAudioSession.sharedInstance()
try? audioSession.setCategory(AVAudioSessionCategoryPlayback)
try? audioSession.setMode(AVAudioSessionModeDefault)
try? audioSession.setActive(true)
audioSession.addObserver(self, forKeyPath: "outputVolume", options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
print(AVAudioSession.sharedInstance().outputVolume)
}
}