Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift AVPlayerViewController Add AirPlay

I'm attempting to enable AirPlay with my AVPlayerViewController. In the document:

https://developer.apple.com/reference/avkit/avplayerviewcontroller

It states

AVPlayerViewController automatically supports AirPlay, but you need to perform some project and audio session configuration before it can be enabled in your application.

Under the Capabilities tab, I did enable the Background Mode for Audio, AirPlay, and Picture in Picture. I have created the AVPlayerViewController as follows:

// Create the view controller and player
let moviePlayerViewController: AVPlayerViewController = AVPlayerViewController()
let moviePlayer = AVPlayer(url: videoUrl!)

moviePlayer.allowsExternalPlayback = true
moviePlayer.usesExternalPlaybackWhileExternalScreenIsActive = true

// Initialize the AVPlayer
moviePlayerViewController.player = moviePlayer

// Present movie player and play when completion
self.present(moviePlayerViewController, animated: false, completion: {
    moviePlayerViewController.player?.play()
})

I thought the two lines

moviePlayer.allowsExternalPlayback = true
moviePlayer.usesExternalPlaybackWhileExternalScreenIsActive = true

Would add the AirPlay support but I'm wrong. I have read that AirPlay can be used by adding MPVolumeView, but that's for a custom video controller, not the built in one. Any help would be greatly appreciated.

like image 725
Mike Walker Avatar asked Feb 07 '17 19:02

Mike Walker


1 Answers

You should still be able to use MPVolumeView. Just use the following:

    let volumeView = MPVolumeView()
    self.view.addSubview(volumeView)

or if you just want the menu to show up, you can use:

    let volumeView = MPVolumeView(frame: CGRect(x: -100, y: 0, width: 0, height: 0))
    self.addSubview(volumeView)
    for view: UIView in volumeView.subviews {
        if let button = view as? UIButton {
            button.sendActions(for: .touchUpInside)
            volumeView.removeFromSuperview()
            break
        }
    }

This will put it outside of the current view and then trigger the action that displays the air play menu.

like image 104
zoecarver Avatar answered Nov 04 '22 13:11

zoecarver