[SOLVED] Detect hardware volume button press when volume not changed

Issue

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?

Solution

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

Answered By – clawesome

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.