Swift 3.1 获取手机音量

获取手机音量

   import AudioToolbox
   let audioSession = AVAudioSession.sharedInstance()
   let volume = audioSession.outputVolume

监听手机音量变化

   do {
        try audioSession.setActive(true)
        audioSession.addObserver(self, forKeyPath: "outputVolume", options: .new, context: nil)

    } catch let error {
        print(error.localizedDescription)
    }

监听方法

   override func observeValue(forKeyPath keyPath: String?,
                           of object: Any?,
                           change: [NSKeyValueChangeKey : Any]?,
                           context: UnsafeMutableRawPointer?) {
         if keyPath == "outputVolume" {
            print(change?[.newKey]! as Any)
         }
    }

设置音量

let volumeView = MPVolumeView()
var slider :UISlider?
override func viewDidLoad() {
    super.viewDidLoad()
    MPVolumeSettingsAlertHide()//隐藏音量提示框

    view.addSubview(volumeView)
    let subviews = volumeView.subviews.filter({ (view) -> Bool in
        print(view)
        return (NSStringFromClass(type(of: view)) == "MPVolumeSlider")
     })
     if subviews.count > 0 {
        slider = subviews.first as? UISlider
        slider?.setValue(1, animated: true)//设置音量
        print("\(slider!.value)")
      }
}

你可能感兴趣的:(Swift 3.1 获取手机音量)