Reputation: 33
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?
Upvotes: 2
Views: 3783
Reputation: 1319
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
Upvotes: 8