使用時:
//定義滑動條用於顯示音量 @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() }