作者:北冥其名 | 来源:互联网 | 2023-05-22 12:50
未调用音量按钮通知功能.
码:
func listenVolumeButton(){
// Option #1
NSNotificationCenter.defaultCenter().addObserver(self, selector: "volumeChanged:", name: "AVSystemController_SystemVolumeDidChangeNotification", object: nil)
// Option #2
var audioSession = AVAudioSession()
audioSession.setActive(true, error: nil)
audioSession.addObserver(self, forKeyPath: "volumeChanged", options: NSKeyValueObservingOptions.New, context: nil)
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer) {
if keyPath == "volumeChanged"{
print("got in here")
}
}
func volumeChanged(notification: NSNotification){
print("got in here")
}
listenVolumeButton()
正在viewWillAppear中调用
"got in here"
在任何一种情况下,代码都没有进入print语句.
我正在尝试两种不同的方法来实现它,两种方式都不起作用.
我跟着这个:检测iPhone音量按钮向上按?
1> rakeshbs..:
使用第二种方法,键路径的值应该是"outputVolume"
.这是我们正在观察的财产.所以将代码更改为,
func listenVolumeButton(){
let audioSession = AVAudioSession.sharedInstance()
audioSession.setActive(true, error: nil)
audioSession.addObserver(self, forKeyPath: "outputVolume",
options: NSKeyValueObservingOptions.New, context: nil)
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject,
change: [NSObject : AnyObject], context: UnsafeMutablePointer) {
if keyPath == "outputVolume"{
print("got in here")
}
}
当音量最大时,是否仍然可以收到通知?
有没有人在swift 3中的github上有一些代码示例?
2> Matthijs..:
上面的代码在Swift 3中不起作用,在这种情况下,试试这个:
func listenVolumeButton() {
do {
try audioSession.setActive(true)
} catch {
print("some error")
}
audioSession.addObserver(self, forKeyPath: "outputVolume", options: NSKeyValueObservingOptions.new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "outputVolume" {
print("got in here")
}
}
这对我不起作用-至少在模拟器中不起作用。