0

When the iPhone is silent then after pressing the volume up button the phone goes to ringer state. How to catch this volume button pressed? Is there any method to catch the button pressed while any media is playing. I have tried code and it is working hen the physical silent key is operating i.e. when I am using the physical mute switch to silent the phone then the media player sound turning off and then again I am making it to ringer using the switch then the sound is again turned on. But when it is on silent pressing the volume up button then the iPhone is going into ringer mode but the media player sound is still off.

I am using AVAudioPlayer to play the media. I have tried using this but it is not working except the above scenario. I have also used AVSystemController_SystemVolumeDidChangeNotification but it is not also working as the method is deprecated and Apple does not give any access to control or getting any notification on when the hardware button is pressed.

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.soloAmbient)
    } catch {
        print("AVAudioSessionCategorySoloAmbient not work")
    }
B K.
  • 534
  • 5
  • 18
  • see this for help : [detect up volume change swift](https://stackoverflow.com/questions/39402223/detect-up-volume-change-swift) – Anbu.Karthik Aug 27 '19 at 11:25
  • https://stackoverflow.com/a/28474014/4350052 worked for me – Stefan Aug 27 '19 at 11:25
  • I guess you want to play audio while the physical mute is switched on right? You should use `AVAudioSession.Category.playback` in this case – MohyG Aug 27 '19 at 11:29
  • Possible duplicate of [Detect volume button press](https://stackoverflow.com/questions/28471481/detect-volume-button-press) – Said Alır Aug 27 '19 at 12:05

1 Answers1

0
func observeVolumeButton(){

    let audioSession = AVAudioSession.sharedInstance()
    audioSession.setActive(true, error: nil)
    audioSession.addObserver(self, forKeyPath: "volume",
        options: NSKeyValueObservingOptions.New, context: nil)
}

override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject,
    change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
    if keyPath == "volume"{
        //see the volume here
    }
}
User123335511231
  • 11,654
  • 4
  • 18
  • 22
  • Wrote the set of code in AppDelegate and calling the observeVolumeButton function on didfinishLaunchingwithoptions. But the method is not observing any events. – Tanmoy Ash Sep 06 '19 at 10:52