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()
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM