Swift3 获取系统音量和监听系统音量

 

使用时:

  //定义滑动条用于显示音量
  @IBOutlet weak var volumSlider: UISlider!

 

 //处理声音,获取当前音量,并添加监听
 handleVolum()

方法内容:

 func handleVolum() {
        do{
            try AVAudioSession.sharedInstance().setActive(true)
        }catch let error as NSError{
            print("\(error)")
        }
     //获取并赋值 volumSlider.value
= AVAudioSession.sharedInstance().outputVolume
     //添加监听 NotificationCenter.
default.addObserver(self, selector: #selector(self.changeVolumSlider), name: NSNotification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object: nil) UIApplication.shared.beginReceivingRemoteControlEvents() }

 

如果按动侧边栏音量键,跟随改变界面内的音量

 func changeVolumSlider(notifi:NSNotification) {
        if let volum:Float = notifi.userInfo?["AVSystemController_AudioVolumeNotificationParameter"] as! Float?{
            volumSlider.value = volum
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
        UIApplication.shared.endReceivingRemoteControlEvents()
    }

 

posted @ 2017-03-17 09:54  那一抹风情  阅读(2002)  评论(0编辑  收藏  举报