Swift AVPlayerViewController添加AirPlay

时间:2017-02-07 19:33:54

标签: ios swift avplayer airplay avplayerviewcontroller

我尝试使用AVPlayerViewController启用AirPlay。在文件中:

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

说明

  

AVPlayerViewController自动支持AirPlay,但您需要先执行一些项目和音频会话配置,然后才能在应用程序中启用它。

Capabilities标签下,我确实启用了音频,AirPlay和画中画的背景模式。我创建了AVPlayerViewController如下:

// 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()
})

我想到了两行

moviePlayer.allowsExternalPlayback = true
moviePlayer.usesExternalPlaybackWhileExternalScreenIsActive = true

会添加AirPlay支持,但我错了。我已经读过可以通过添加MPVolumeView来使用AirPlay,但这是用于自定义视频控制器,而不是内置的。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

您仍然可以使用MPVolumeView。只需使用以下内容:

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

或者如果您只想显示菜单,可以使用:

    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
        }
    }

这会将其置于当前视图之外,然后触发显示空中播放菜单的操作。