Programmatically set device volume using MPVolumeView (iOS Swift)

January 22, 2019

Often times in an application you want to be able to allow the user to change the output volume of the app. There is no easy way to achieve this so we need to use a workaround by leveraging the MPVolumeView. Lets see how:

Add this extension:

import MediaPlayer

extension MPVolumeView {
    static func setVolume(_ volume: Float) {
        // Need to use the MPVolumeView in order to change volume, but don't care about UI set so frame to .zero
        let volumeView = MPVolumeView(frame: .zero)
        // Search for the slider
        let slider = volumeView.subviews.first(where: { $0 is UISlider }) as? UISlider
        // Update the slider value with the desired volume.
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.01) {
            slider?.value = volume
        }
        // Optional - Remove the HUD
        if let app = UIApplication.shared.delegate as? AppDelegate, let window = app.window {
            volumeView.alpha = 0.000001
            window.addSubview(volumeView)
        }
    }
}

Usage:

MPVolumeView.setVolume(0.5) // Set volume to 50%