0

I get the sound value from the audioSession and put it into the Slider. But how can I do the opposite? If I pass a value from the slider to the player.volume the volume changes, but then when MPNowPlayingInfoCenter is running, these changes are not visible in it. And if I change volume with hardware buttons changes also are not visible in slider. I need to link all volume changes into one. So that when I change the value of the Slider, the sound changes in MPNowPlayingInfoCenter. Thanks for any advice. My code:

...
var outputVolumeObserve: NSKeyValueObservation?
let audioSession = AVAudioSession.sharedInstance()

func listenVolumeButton() {
        do {
            try audioSession.setActive(true)
        } catch {}

        outputVolumeObserve = audioSession.observe(\.outputVolume) { (audioSession, changes) in
            self.volumeSlider.value = audioSession.outputVolume
        }
    }

@IBAction func handleVolumeSlider(_ sender: Any) {
        player.volume = volumeSlider.value
   }
VyacheslavB
  • 181
  • 9

1 Answers1

0

I solved the problem by changing the volume value of the MPVolumeView:

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
        }
    }
}

...
@IBAction func handleVolumeSlider(_ sender: Any) {
        MPVolumeView.setVolume(volumeSlider.value)
    }
VyacheslavB
  • 181
  • 9