1、需要用到的库:
2、重写 viewDidAppear
方法,添加监听事件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) do{ try AVAudioSession.sharedInstance().setActive(true) }catch let error as NSError{ print("\(error)") } let volumeView = MPVolumeView(frame: .zero) volumeView.clipsToBounds = true view.addSubview(volumeView) NotificationCenter.default.addObserver(self, selector: #selector(self.changeVolumeSlider), name: NSNotification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object: nil) UIApplication.shared.beginReceivingRemoteControlEvents() }
|
3、实现监听事件:
1 2 3 4 5
| @objc func changeVolumeSlider(notifi: NSNotification) { let volume = notifi.userInfo!["AVSystemController_AudioVolumeNotificationParameter"] as! Float print(volume) }
|
4、重写 viewDidDisappear
方法,取消监听:
1 2 3 4 5 6 7 8 9 10 11
| override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) do{ try AVAudioSession.sharedInstance().setActive(false) }catch let error as NSError{ print("\(error)") } NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object:nil) UIApplication.shared.endReceivingRemoteControlEvents() }
|