1.开启后台模式
image.png
2.导入框架#import <AVKit/AVKit.h> 创建AVPictureInPictureController
注:如果是使用系统播放器AVPlayerViewController,设置allowsPictureInPicturePlayback = YES即可
//1.判断是否支持画中画功能 if ([AVPictureInPictureController isPictureInPictureSupported]) { //2.开启权限 @try { NSError *error = nil; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionOrientationBack error:&error]; [[AVAudioSession sharedInstance] setActive:YES error:&error]; } @catch (NSException *exception) { NSLog(@"AVAudioSession发生错误"); } self.pipVC = [[AVPictureInPictureController alloc] initWithPlayerLayer:self.player]; self.pipVC.delegate = self; }
3.开启或关闭画中画
if (self.pipVC.isPictureInPictureActive) { [self.pipVC stopPictureInPicture]; } else { [self.pipVC startPictureInPicture]; }
4.代理 AVPictureInPictureControllerDelegate
// 即将开启画中画 - (void)pictureInPictureControllerWillStartPictureInPicture:(AVPictureInPictureController *)pictureInPictureController; // 已经开启画中画 - (void)pictureInPictureControllerDidStartPictureInPicture:(AVPictureInPictureController *)pictureInPictureController; // 开启画中画失败 - (void)pictureInPictureController:(AVPictureInPictureController *)pictureInPictureController failedToStartPictureInPictureWithError:(NSError *)error; // 即将关闭画中画 - (void)pictureInPictureControllerWillStopPictureInPicture:(AVPictureInPictureController *)pictureInPictureController; // 已经关闭画中画 - (void)pictureInPictureControllerDidStopPictureInPicture:(AVPictureInPictureController *)pictureInPictureController; // 关闭画中画且恢复播放界面 - (void)pictureInPictureController:(AVPictureInPictureController *)pictureInPictureController restoreUserInterfaceForPictureInPictureStopWithCompletionHandler:(void (^)(BOOL restored))completionHandler;
值得注意的是,关闭画中画会执行
pictureInPictureController:restoreUserInterfaceForPictureInPictureStopWithCompletionHandler: 这个代理方法,用来恢复播放界面的
全局画中画注意点
- 通过一个全局变量持有画中画控制器,可以在pictureInPictureControllerWillStartPictureInPicture持有,pictureInPictureControllerDidStopPictureInPicture释放;
- 有可能不是点画中画按钮,而是从其它途径来打开当前画中画控制器,可以在viewWillAppear 进行判断并关闭;
- 已有画中画的情况下开启新的画中画,需要等完全关闭完再开启新的,防止有未知的错误出现,因为关闭画中画是有过程的;
- 如果创建AVPictureInPictureController并同时开启画中画功能,有可能会失效,出现这种情况延迟开启画中画功能即可。