2

I need to detect the sound volume button click. Solution in Detect volume button press and used by me work only when sounds volume changed. I need to detect sound volume button click. For example when the sound has max level and the user clicks up level button this solution was not work.

 let audioSession = AVAudioSession.sharedInstance()
    self.obs = audioSession.observe( \.outputVolume ) { (av, change) in
    print("volume \(av.outputVolume)")
 }

Are there any other working solutions to detect a sound volume button press?

smikhlevskiy
  • 33
  • 1
  • 7
  • Whether or not you find a way to detect it, you may want to check Apple's [Review Guidelines](https://developer.apple.com/app-store/review/guidelines/) - specifically: **2.5.9** *Apps that alter or disable the functions of standard switches, such as the Volume Up/Down and Ring/Silent switches, or other native user interface elements or behaviors will be rejected.* – DonMag Jan 13 '20 at 15:23
  • Does this answer your question? [Detect volume button press](https://stackoverflow.com/questions/28471481/detect-volume-button-press) – Scriptable Jan 13 '20 at 15:31
  • I do not want to alter or disable the functions of standard volume. I need only detect click, in case when volume not changed. – smikhlevskiy Jan 13 '20 at 15:31
  • Instagram app detecting volume button click in this case(when volume is max) – smikhlevskiy Jan 13 '20 at 15:32
  • https://stackoverflow.com/questions/28471481/detect-volume-button-press in this solution detecting change sound volume and not work when volume not changed. for example when sound is max and user click up – smikhlevskiy Jan 13 '20 at 15:38

1 Answers1

7
let volumeView = MPVolumeView(frame: CGRect.zero)
self.view.addSubview(volumeView)
NotificationCenter.default.addObserver(self, selector: #selector(volumeChanged(_:)), name: NSNotification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object: nil)

This will get called every press regardless of volume level

@objc func volumeChanged(_ notification: NSNotification) {
    if let volume = notification.userInfo!["AVSystemController_AudioVolumeNotificationParameter"] as? Float {
        print("volume: \(volume)")
    }
}

output:

volume: 0.8125
volume: 0.875
volume: 0.9375
volume: 1.0
volume: 1.0
volume: 1.0
volume: 1.0
clawesome
  • 1,223
  • 1
  • 5
  • 10