Search code examples
iosswiftmpmusicplayercontrollermpvolumeview

Adjusting the Volume using MPVolume for a music player, iOS


I am trying to figure out how to change the volume of a music track being played and I am using MPMusicPlayerController to import a song from the Music library.

I have tried to use MPVolume by adding a UIView and subclassing it to MPVolume. But it does not show in the view as I thought it would. I am probably doing it all wrong. I am new to this and the apple docs aren't showing me a clear path.

Does anyone know how to do it.

I also tried adding a slider and with the following code was told the MPMusicPlayerController.applicationMusicPlayer().volume was deprecated.

This was my attempt with a slider:

 @IBAction func volumeSliderChanging(sender: UISlider) {

        MPMusicPlayerController.applicationMusicPlayer().volume = self.volumeChange.value


    }

Thanks in advance.


Solution

  • Try to launch your project on the real device. The simulator doesn't display MPVolumeSlider.

    Use this code, what by means of UISlider to change value of a system sound:

    @IBAction func volumeSliderChanging(sender: UISlider) {
        let volumeSlider = (MPVolumeView().subviews.filter { NSStringFromClass($0.classForCoder) == "MPVolumeSlider" }.first as! UISlider)    
        volumeSlider.setValue(sender.value, animated: false)
    }
    

    Be convinced that MediaPlayer framework is connected:

    import MediaPlayer
    

    Good luck!