How to change device Volume on iOS - not music volume

后端 未结 9 647
旧时难觅i
旧时难觅i 2020-11-28 10:30

I want to change the device volume on iOS (iphone).

I know that i can change the volume of music library with this lines below:

//implement at firs         


        
相关标签:
9条回答
  • 2020-11-28 11:28

    Call listenVolumeButton in your viewDidLoad and replace the // line with whatever you want to do.

    private func listenVolumeButton() {
        let audioSession = AVAudioSession.sharedInstance()
        try? audioSession.setActive(true)
        audioSession.addObserver(self,
                                 forKeyPath: "outputVolume",
                                 options: NSKeyValueObservingOptions.new,
                                 context: nil)
    
        hideVolumeView()
    }
    
    private func hideVolumeView() {
        let volumeView = MPVolumeView(frame: CGRect.zero)
        for subview in volumeView.subviews {
            if let button = subview as? UIButton {
                button.setImage(nil, for: .normal)
                button.isEnabled = false
                button.sizeToFit()
            }
        }
        UIApplication.shared.windows.first?.addSubview(volumeView)
        UIApplication.shared.windows.first?.sendSubviewToBack(volumeView)
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
        switch keyPath {
        case "outputVolume":
            guard let systemSlider = MPVolumeView().subviews.first(where: { NSStringFromClass($0.classForCoder) == "MPVolumeSlider" }) as? UISlider else {
                return
            }
    
            let avoidLimitsValue = max(min(AVAudioSession.sharedInstance().outputVolume, Float(0.9)), Float(0.1))
    
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.01) {
                systemSlider.setValue(avoidLimitsValue, animated: false)
            }
    
            // DO YOUR STUFF HERE
        default:
            break
        }
    }
    
    0 讨论(0)
  • 2020-11-28 11:33

    Here's what I've done:

    func setSystemVolume(volume: Float) {
        let volumeView = MPVolumeView()
    
        for view in volumeView.subviews {
            if (NSStringFromClass(view.classForCoder) == "MPVolumeSlider") {
                let slider = view as! UISlider
                slider.setValue(volume, animated: false)
            }
        }
    }
    

    As property volume in MPMusicPlayerController was deprecate in iOS 7. This is only method you can do that.

    0 讨论(0)
  • 2020-11-28 11:35

    Swift 3 - I use this:

    func setVolumeTo(volume: Float) {
      (MPVolumeView().subviews.filter{NSStringFromClass($0.classForCoder) == "MPVolumeSlider"}.first as? UISlider)?.setValue(volume, animated: false)
    }
    
    0 讨论(0)
提交回复
热议问题