我正在设计一个允许用户在 SwiftUI 视图中查看特定视频的应用程序。我想支持画中画,并且 AVPictureInPictureController.isPictureInPictureSupported() 总是返回 true,而 pipController.isPictureInPicturePossible 有时会返回 true,但通常不会在视频实际播放时返回。我可能误解了如何使用 AVPictureInPictureController。
我的应用程序使用以下代码初始化了一个名为 FullScreenVideoView 的视图:
init(player: KHKVideoPlayer, aspectRatio: CGFloat, presentingViewController pvc: UIViewController?) {
self.aspectRatio = aspectRatio
self.pvc = pvc
self.model = FullScreenVideoViewerModel(player: player)
self.playerController = KHKPlayerController(player: player.avPlayer, cornerRadius: 0)
if AVPictureInPictureController.isPictureInPictureSupported() {
self.pipController = AVPictureInPictureController(playerLayer: AVPlayerLayer(player: player.avPlayer))!
}
self.isMuted = player.avPlayer.isMuted
}
然后,在视图主体中,它通过调用在初始化程序中定义的 playerController 来显示视频:
playerController
.frame(height: aspectRatio * geometry.size.width)
.onTapGesture {
if self.model.player.avPlayer.isPlaying {
self.model.pause()
} else {
self.model.play()
}
}
playerController 是 AVPlayerViewController 的包装器:
struct KHKPlayerController: UIViewControllerRepresentable {
typealias UIViewControllerType = AVPlayerViewController
var player: AVPlayer
var cornerRadius: CGFloat?
init(player: AVPlayer) {
self.player = player
}
init(player: AVPlayer, cornerRadius: CGFloat) {
self.player = player
self.cornerRadius = cornerRadius
}
func makeUIViewController(context: Context) -> AVPlayerViewController {
let playerVC = AVPlayerViewController()
playerVC.showsPlaybackControls = false
playerVC.player = player
playerVC.view.layer.masksToBounds = true
playerVC.view.layer.cornerRadius = cornerRadius ?? 8
return playerVC
}
func updateUIViewController(_ uiViewController: AVPlayerViewController, context: Context) {
}
}
一个按钮应该启动 PiP:
RectangleButton(action: {
print("pip is possible: \(pipController?.isPictureInPicturePossible ?? false)")
pipController?.startPictureInPicture()
}, imageSystemName: "pip.enter", foregroundColor: UI.Constants.primaryColor, backgroundColor: UI.Constants.tertiaryColor, width: 35, height: 25, cornerRadius: 3)
任何帮助将非常感激。我找不到任何有关在 SwiftUI 中启动 PiP 的有用信息。
注意 - 启用了正确的后台功能。另外,在我的 AppDelegate didFinishLaunchingWithOptions 方法中,我有这个 PiP 似乎需要的代码:
do {
try audioSession.setCategory(AVAudioSession.Category.playback)
} catch {
print("Audio session failed")
}