I want to change the device volume on iOS (iphone).
I know that i can change the volume of music library with this lines below:
//implement at firs
Call listenVolumeButton
in your viewDidLoad
and replace the //
line with whatever you want to do.
private func listenVolumeButton() {
let audioSession = AVAudioSession.sharedInstance()
try? audioSession.setActive(true)
audioSession.addObserver(self,
forKeyPath: "outputVolume",
options: NSKeyValueObservingOptions.new,
context: nil)
hideVolumeView()
}
private func hideVolumeView() {
let volumeView = MPVolumeView(frame: CGRect.zero)
for subview in volumeView.subviews {
if let button = subview as? UIButton {
button.setImage(nil, for: .normal)
button.isEnabled = false
button.sizeToFit()
}
}
UIApplication.shared.windows.first?.addSubview(volumeView)
UIApplication.shared.windows.first?.sendSubviewToBack(volumeView)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
switch keyPath {
case "outputVolume":
guard let systemSlider = MPVolumeView().subviews.first(where: { NSStringFromClass($0.classForCoder) == "MPVolumeSlider" }) as? UISlider else {
return
}
let avoidLimitsValue = max(min(AVAudioSession.sharedInstance().outputVolume, Float(0.9)), Float(0.1))
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.01) {
systemSlider.setValue(avoidLimitsValue, animated: false)
}
// DO YOUR STUFF HERE
default:
break
}
}