Just added a property in the class:
private var audioLevel : Float = 0.0
and completed as follows.
func listenVolumeButton(){
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setActive(true, options: [])
audioSession.addObserver(self, forKeyPath: "outputVolume",
options: NSKeyValueObservingOptions.new, context: nil)
audioLevel = audioSession.outputVolume
} catch {
print("Error")
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "outputVolume"{
let audioSession = AVAudioSession.sharedInstance()
if audioSession.outputVolume > audioLevel {
print("Hello")
}
if audioSession.outputVolume < audioLevel {
print("GoodBye")
}
audioLevel = audioSession.outputVolume
print(audioSession.outputVolume)
}
}
Tested, it works.
Hello
0.375
GoodBye
0.3125
You could improve a little : if the level is already at max, pressing the up button will not change the value (simlilarly at min)
You could set the system volume to 0.9375 or 0.0625 when at max or at min (that would be minimal disturbance for user, but not perfect)
(values are coded on 4 bits, 16 values between 0 and 1)
This gets it done:
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "outputVolume"{
let audioSession = AVAudioSession.sharedInstance()
if audioSession.outputVolume > audioLevel {
print("Hello")
audioLevel = audioSession.outputVolume
}
if audioSession.outputVolume < audioLevel {
print("GoodBye")
audioLevel = audioSession.outputVolume
}
if audioSession.outputVolume > 0.999 {
(MPVolumeView().subviews.filter{NSStringFromClass($0.classForCoder) == "MPVolumeSlider"}.first as? UISlider)?.setValue(0.9375, animated: false)
audioLevel = 0.9375
}
if audioSession.outputVolume < 0.001 {
(MPVolumeView().subviews.filter{NSStringFromClass($0.classForCoder) == "MPVolumeSlider"}.first as? UISlider)?.setValue(0.0625, animated: false)
audioLevel = 0.0625
}
}
}
But take care, changing the system setting could cause problem for App store.
Solution completed from : https://stackoverflow.com/questions/36322856/swift-how-to-set-the-iphone-volume-programmatically