iOS 9: How to change volume programmatically witho

2019-01-05 04:11发布

I have to change the volume on iPad and using this code:

[[MPMusicPlayerController applicationMusicPlayer] setVolume:0];

But this changing volume and showing system volume bar on iPad. How to change the sound without showing the volume bar?

I know, setVolume: is deprecated, and everybody says to use MPVolumeView. If this is the only way to solve my problem, then how to change the volume using MPVolumeView? I don't see any method in MPVolumeView that changes the sound.
Should I use some another class together with MPVolumeView?

But it's preferable to use MPMusicPlayerController.

Thank you for advice!

9条回答
祖国的老花朵
2楼-- · 2019-01-05 04:32

For 2018, working on iOS 11.4

You need to change slider.value after a small delay.

extension MPVolumeView {
  static func setVolume(_ volume: Float) {
    let volumeView = MPVolumeView()
    let slider = volumeView.subviews.first(where: { $0 is UISlider }) as? UISlider

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.01) {
      slider?.value = volume
    }
  }
}

Usage:

MPVolumeView.setVolume(0.5)

Objective-C version

查看更多
SAY GOODBYE
3楼-- · 2019-01-05 04:34

Version: Swift 3 & Xcode 8.1

extension MPVolumeView {
    var volumeSlider:UISlider { // hacking for changing volume by programing
        var slider = UISlider()
        for subview in self.subviews {
            if subview is UISlider {
                slider = subview as! UISlider
                slider.isContinuous = false
                (subview as! UISlider).value = AVAudioSession.sharedInstance().outputVolume
                return slider
            }
        }
        return slider
    }
}
查看更多
祖国的老花朵
4楼-- · 2019-01-05 04:36

Here's a solution in Swift. It might be a shady one, so I'll let you know if Apple approved this when I publish. Meantime, this works just fine for me:

  1. Define an MPVolumeView and an optional UISlider in your View Controller

    private let volumeView: MPVolumeView = MPVolumeView()
    private var volumeSlider: UISlider?
    
  2. In the storyboard, define a view that's hidden from the user (height=0 should do the trick), and set an outlet for it (we'll call it hiddenView here). This step is only good if you want NOT to display the volume HUD when changing the volume (see note below):

    @IBOutlet weak var hiddenView: UIView!
    
  3. In viewDidLoad() or somewhere init-y that runs once, catch the UISlider that actually controls the volume into the optional UISlider from step (1):

    override func viewDidLoad() {
        super.viewDidLoad()
    
        ...
    
        hiddenView.addSubview(volumeView)
        for view in volumeView.subviews {
            if let vs = view as? UISlider {
                volumeSlider = vs
                break
            }
        }
    }
    
  4. When you want to set the volume in your code, just set volumeSlider?.value to be anywhere between 0.0 and 1.0, e.g. for increasing the volume:

    func someFunc() {
        if volumeSlider?.value < 0.99 {
            volumeSlider?.value += 0.01
        } else {
            volumeSlider?.value = 1.0
        }
    }
    

Important note: This solution will prevent the iPhone's Volume HUD from appearing - either when you change the volume in your code, or when the user clicks the external volume buttons. If you do want to display the HUD, then skip all the hidden view stuff, and don't add the MPVolumeView as a subview at all. This will cause iOS to display the HUD when the volume changes.

查看更多
女痞
5楼-- · 2019-01-05 04:39

@udjat 's answer in Swift 3

extension MPVolumeView {
    var volumeSlider: UISlider? {
        showsRouteButton = false
        showsVolumeSlider = false
        isHidden = true
        for subview in subviews where subview is UISlider {
            let slider =  subview as! UISlider
            slider.isContinuous = false
            slider.value = AVAudioSession.sharedInstance().outputVolume
            return slider
        }
        return nil
    }
}
查看更多
手持菜刀,她持情操
6楼-- · 2019-01-05 04:40
extension UIViewController {
  func setVolumeStealthily(_ volume: Float) {
    guard let view = viewIfLoaded else {
      assertionFailure("The view must be loaded to set the volume with no UI")
      return
    }

    let volumeView = MPVolumeView(frame: .zero)

    guard let slider = volumeView.subviews.first(where: { $0 is UISlider }) as? UISlider else {
      assertionFailure("Unable to find the slider")
      return
    }

    volumeView.clipsToBounds = true
    view.addSubview(volumeView)

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) { [weak slider, weak volumeView] in
      slider?.setValue(volume, animated: false)
      DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) { [weak volumeView] in
        volumeView?.removeFromSuperview()
      }
    }
  }
}

Usage:

// set volume to 50%
viewController.setVolume(0.5)
查看更多
乱世女痞
7楼-- · 2019-01-05 04:42

Swift > 2.2, iOS > 8.0,

I didn't find any solution I was looking but I end up doing this as solution:

let volumeView = MPVolumeView()

override func viewDidLoad() {
    ...
    view.addSubview(volumeView)
    volumeView.alpha = 0.00001
}

func changeSpeakerSliderPanelControls(volume: Float) {
    for subview in self.volumeView.subviews {

        if subview.description.rangeOfString("MPVolumeSlider") != nil {
             let slider = subview as! UISlider
             slider.value = volume

             break
        }
    }
}
查看更多
登录 后发表回答