Set the slider value based on the AVAudiosession volume || mobile system volume based slider change in iOS swift
Solution:
If you are adjusting the volume in your phone volume button based on slider change you can follow the below steps
when initially set the value to your slider then follow the below steps.If you tap play button then slider will set the default value
you must have to do the below steps in disappear otherwise app will crash
If you are adjusting the volume in your phone volume button based on slider change you can follow the below steps
override func viewDidDisappear(_ animated: Bool) {
AVAudioSession.sharedInstance().removeObserver(self, forKeyPath: "outputVolume")
do { try AVAudioSession.sharedInstance().setActive(false) }
catch { debugPrint("\(error)") }
}
func listenVolumeButton() {
let audioSession = AVAudioSession.sharedInstance()
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")
volumeBar.setValue((AVAudioSession.sharedInstance().outputVolume*10), animated: true)
}
}
when initially set the value to your slider then follow the below steps.If you tap play button then slider will set the default value
// MARK: - DidTapOnPlay
@IBAction func didTapOnPlay(_ sender: Any) {
print("audio",AVAudioSession.sharedInstance().outputVolume)
let session = AVAudioSession.sharedInstance()
do {
try session.setActive(true)
} catch let error as NSError {
print(error.localizedDescription)
}
print("audio",session.outputVolume)
volumeBar.setValue((session.outputVolume*10), animated: true)
}you must have to do the below steps in disappear otherwise app will crash
override func viewDidDisappear(_ animated: Bool) {
AVAudioSession.sharedInstance().removeObserver(self, forKeyPath: "outputVolume")
do { try AVAudioSession.sharedInstance().setActive(false) }
catch { debugPrint("\(error)") }
}
Comments
Post a Comment