iOS音视频开发 PictureInPicture

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/szk972092933/article/details/82769053

Picture in Picture (PiP)在是iOS9新添加的功能,允许iPad用户在悬浮小窗口播放视频。效果如下

Figure 4-1  PiP in Action

 你可以使用AVKit framework的AVPlayerViewController类来实现,或者如果自定义了播放器,使用AVPictureInPictureController来实现。在使用AVPlayerViewController来播放视频时,当你设置AVAudioSession的category为AVAudioSessionCategoryPlayback时,系统默认就支持这种功能。当用户点击最左边的按钮,退出这种播放模式时,播放界面会恢复到正常情况,但是播放会停止,你需要实现AVPlayerViewControllerDelegate代理,来处理这种情况

func playerViewController(_ playerViewController: AVPlayerViewController,
                          restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: (Bool) -> Void) {
    present(playerViewController, animated: true) {
        completionHandler(false)
    }
}

在自己写的播放器里实现PiP效果需要自定义UI界面,需要检测系统是否自持这种播放效果

func setupPictureInPicture() {
    // Ensure PiP is supported by current device
    if AVPictureInPictureController.isPictureInPictureSupported() {
        // Create new controller passing reference to the AVPlayerLayer
        pictureInPictureController = AVPictureInPictureController(playerLayer: playerLayer)
        pictureInPictureController.delegate = self
        let keyPath = #keyPath(AVPictureInPictureController.isPictureInPicturePossible)
        pictureInPictureController.addObserver(self,
                                               forKeyPath: keyPath,
                                               options: [.initial, .new],
                                               context: &pictureInPictureControllerContext)
    } else {
        // PiP not supported by current device. Disable PiP button.
        pictureInPictureButton.isEnabled = false
    }
}

使用pictureInPictureController.stopPictureInPicture()和pictureInPictureController.startPictureInPicture()方法来实现开始和关闭PiP播放模式,通过以下代理方法监听,生命周期事件

func pictureInPictureControllerWillStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
    // hide playback controls
    // show placeholder artwork
}
 
func pictureInPictureControllerDidStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
    // hide placeholder artwork
    // show playback controls
}

猜你喜欢

转载自blog.csdn.net/szk972092933/article/details/82769053