前言
今天更新了iOS14,iOS14可以支持畫中畫功能处坪,閑著無聊驾茴,來寫個代碼實現(xiàn)。
話不多說事格,先上Demo PictureInPictureDemo
效果圖
基本使用
1惕艳、打開Xcode,開啟后臺模式
2驹愚、打開畫中畫權(quán)限
-(void)openAccess{
@try {
NSError *error = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
[[AVAudioSession sharedInstance] setActive:YES error:&error];
} @catch (NSException *exception) {
NSLog(@"AVAudioSession發(fā)生錯誤");
}
}
3远搪、初始化畫中畫控制器
-(void)setupPictureInPicture{
NSURL *urlVideo = [[NSBundle mainBundle]URLForResource:@"v1" withExtension:@"MP4"];
AVAsset *asset = [AVAsset assetWithURL:urlVideo];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];
self.player = [AVPlayer playerWithPlayerItem:playerItem];
self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
self.playerLayer.frame = self.view.frame;
self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
[self.view.layer addSublayer:self.playerLayer];
//1.判斷是否支持畫中畫功能
if ([AVPictureInPictureController isPictureInPictureSupported]) {
self.pipVC = [[AVPictureInPictureController alloc] initWithPlayerLayer:self.playerLayer];
self.pipVC.delegate = self;
}
[self.player play];
}
4、創(chuàng)建按鈕
-(void)creatBtn{
UIButton * switchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[switchBtn setFrame:CGRectMake(20, 20, 50, 40)];
[switchBtn setBackgroundColor:[UIColor blackColor]];
[switchBtn setImage:[UIImage imageNamed:@"Classcenter_draw"] forState:UIControlStateNormal];
[switchBtn addTarget:self action:@selector(switchBtnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview: switchBtn];
}
5逢捺、按鈕點擊方法實現(xiàn)
-(void)switchBtnClick:(UIButton*)sender{
//判斷當(dāng)前是否為畫中畫
if (self.pipVC.isPictureInPictureActive) {
//關(guān)閉畫中畫
[self.pipVC stopPictureInPicture];
} else {
//開始畫中畫
[self.pipVC startPictureInPicture];
}
}
6谁鳍、AVPictureInPictureControllerDelegate代理實現(xiàn)
// 即將開啟畫中畫
- (void)pictureInPictureControllerWillStartPictureInPicture:(AVPictureInPictureController *)pictureInPictureController{
NSLog(@"即將開啟畫中畫");
}
// 已經(jīng)開啟畫中畫
- (void)pictureInPictureControllerDidStartPictureInPicture:(AVPictureInPictureController *)pictureInPictureController{
NSLog(@"已經(jīng)開啟畫中畫");
}
// 開啟畫中畫失敗
- (void)pictureInPictureController:(AVPictureInPictureController *)pictureInPictureController failedToStartPictureInPictureWithError:(NSError *)error{
NSLog(@"開啟畫中畫失敗");
}
// 即將關(guān)閉畫中畫
- (void)pictureInPictureControllerWillStopPictureInPicture:(AVPictureInPictureController *)pictureInPictureController{
NSLog(@"即將關(guān)閉畫中畫");
}
// 已經(jīng)關(guān)閉畫中畫
- (void)pictureInPictureControllerDidStopPictureInPicture:(AVPictureInPictureController *)pictureInPictureController{
NSLog(@"已經(jīng)關(guān)閉畫中畫");
}
// 關(guān)閉畫中畫且恢復(fù)播放界面
- (void)pictureInPictureController:(AVPictureInPictureController *)pictureInPictureController restoreUserInterfaceForPictureInPictureStopWithCompletionHandler:(void (^)(BOOL restored))completionHandler{
NSLog(@"關(guān)閉畫中畫且恢復(fù)播放界面");
}