Change audio output channel in iOS

January 31, 2019

If you application is playing some sort of sound, perhaps music, you want to allow the user to be able to change the output source. Current Apple does not have an easy way for you to programmatically list and display the output source but they have a handy view MPVolumeView to help you out. We can manipulate this to programatically set audio routes.

Let's see how:

import MediaPlayer

extension MPVolumeView {
    static func openAudioRoutes(in view: UIView) {
        let volumeView = MPVolumeView()
        volumeView.showsVolumeSlider = false
        volumeView.showsRouteButton = true
        volumeView.alpha = 0.000001
        view.addSubview(volumeView)
        let button = volumeView.subviews.first(where: { $0 is UIButton }) as? UIButton
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.01) {
            button?.sendActions(for: .touchUpInside)
        }
    }
}

Usage:

MPVolumeView.openAudioRoutes(in: self.view)