【发布时间】:2020-03-17 10:33:32
【问题描述】:
我已经阅读了stackOverFlow和gitHub提供的很多解决方案,它们都对我不起作用。我尝试了以下两种方式:
- 使用音频会话
override func viewWillAppear(_ animated: Bool) {
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setActive(true, options: [])
} catch {
print("error")
}
// this print shows, got the current volume.
//but what I need is the notification of the change of volume
print("view will appear ,this volume is \(audioSession.outputVolume)")
audioSession.addObserver(self,
forKeyPath: "outputVolume",
options: [.new],
context: nil)
}
override class func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
if keyPath == "outputVolume"{
let audioSession = AVAudioSession.sharedInstance()
let volume = audioSession.outputVolume
//this print doesn't shows up
print("observed volume is \(volume)")
}
}
- 使用通知
override func viewWillAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector: #selector(observed(_:)), name: Notification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object: nil)
}
@objc func observed(_ notification: Notification){
print("observed")
}
顺便说一下,我用的是模拟器(iPhone11,iOS13.1),Xcode版本是11.1
【问题讨论】: