简体   繁体   中英

Detect hardware volume button press when volume not changed

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM