1.当前系统音量
AVAuSession属于MediaPlayer,在class前面 import MediaPlayer 即可使用之获取系统当前音量,如下:
ps:一定要setActive(true),一开始就是死在这里
///获取系统音量大小
private func getSystemVolumValue() -> Float {
do{
try AVAudioSession.sharedInstance().setActive(**true**)
}catch let error as NSError{
print("\(error)")
}
let currentVolume = AVAudioSession.sharedInstance().outputVolume
return currentVolume
}
2.监听系统音量变换
使用NSNotificationCenter可以监听到iOS系统的好多动作,这里音量变化监听的动作是:AVSystemController_SystemVolumeDidChangeNotification 代码如下:
///添加监听
func addSystemVolumNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(self.changeVolumSlider), name: NSNotification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object: nil)
UIApplication.shared.beginReceivingRemoteControlEvents()
}
///系统声音变化监听
@objc func changeVolumSlider(notifi:NSNotification) {
if let volum:Float = notifi.userInfo?["AVSystemController_AudioVolumeNotificationParameter"] as! Float?{
print("volum: \(volum)")
}
}
3.调节系统音量大小
///调节系统音量大小
private func setSysVolum(_ value: Float) {
let volumeView = MPVolumeView()
if let view = volumeView.subviews.first as? UISlider {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {//延迟0.01秒就能够正常播放
view.value = value
}
}
}