iOS14 画中画

画中画本质是添加了一个视频悬浮框,demo地址:点我:demo链接,核心实现代码如下

@interface VideoPlayerView()
// 开启画中画播放的权限
if ([AVPictureInPictureController isPictureInPictureSupported]) {
    @try {
        NSError *error = nil;
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
        [[AVAudioSession sharedInstance] setActive:YES error:&error];
    } @catch (NSException *exception) {
        NSLog(@"AVAudioSession发生错误");
    }
    self.pipVC = [[AVPictureInPictureController alloc] initWithPlayerLayer:self.playerLayer];
        self.pipVC.delegate = self;
}    
// 画中画的按钮
- (UIButton *)pipBtn {
    if (!_pipBtn) {
        UIImage *openImage = AVPictureInPictureController.pictureInPictureButtonStartImage;
       
        UIImage *closeImage = AVPictureInPictureController.pictureInPictureButtonStopImage;
        _pipBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_pipBtn setImage:openImage forState:UIControlStateNormal];
        [_pipBtn setImage:closeImage forState:UIControlStateSelected];
        _pipBtn.frame =CGRectMake(CGRectGetMaxX(_bCheck.frame) + 10, CGRectGetMinY(_bCheck.frame) , 44, 44);
        [_pipBtn addTarget:self action:@selector(clickPipBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return  _pipBtn;
}
// 画中画的按钮的响应事件
- (void)clickPipButtonAction {
    if (self.pipVC.isPictureInPictureActive) {
        [self.pipVC stopPictureInPicture];
    } else {
        [self.pipVC startPictureInPicture];
    }
}

注意1、进入画中画模式时播放或者暂停是随着AVPlayer的播放状态
注意2、使用ZFPlayer库时发现,当你在viewDidLoad方法中初始化了AVPictureInPictureController 对象会出现下面两个情况
(1)在关闭画中画后会出现仍然播放的情况;(2)在非画中画模式播放视频时,APP进入后台后会弹出画中画
解决方案:(1)在打开画中画按钮的响应事件中初始化AVPictureInPictureController对象;(2)在已经关闭画中画回调中将AVPictureInPictureController对象置空

 - (void)pictureInPictureControllerWillStopPictureInPicture:(AVPictureInPictureController *)pictureInPictureController  

参考链接和注意事项见:大佬1、大佬2

你可能感兴趣的:(iOS14 画中画)