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
}
}
Here's what I've done:
func setSystemVolume(volume: Float) {
let volumeView = MPVolumeView()
for view in volumeView.subviews {
if (NSStringFromClass(view.classForCoder) == "MPVolumeSlider") {
let slider = view as! UISlider
slider.setValue(volume, animated: false)
}
}
}
As property volume
in MPMusicPlayerController
was deprecate in iOS 7. This is only method you can do that.
Swift 3 - I use this:
func setVolumeTo(volume: Float) {
(MPVolumeView().subviews.filter{NSStringFromClass($0.classForCoder) == "MPVolumeSlider"}.first as? UISlider)?.setValue(volume, animated: false)
}