简体   繁体   中英

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.

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.

Nowadays you should have no problem doing this.

(1) Under the Capabilities tab, enable Background Mode for Audio

(2) With your

var ezPlayer: AVPlayerViewController!

just

    ezPlayer.showsPlaybackControls = true
    ezPlayer.player = AVPlayer(url: ... )

    ezPlayer.player!.allowsExternalPlayback = true
    ezPlayer.player!.usesExternalPlaybackWhileExternalScreenIsActive = 

and you should be fine. Build to a device. Assuming you are on a usable wifi network with an apple TV, apple laptops, the airplay icon will appear and work.

There's no need to use an MPVolumeView these days.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM