最近项目有一部分需要做一个视频播放的功能,找了下,发现AVPlayerViewController可以基本实现所需的功能,但有一点就是AVPlayerViewController全屏时依旧是默认竖屏,必须手动改变设备方向时才会发生旋转,经过各种查资料和摸索,最终实现了默认全屏的方法.代码如下:
//点击一个按钮,开始播放视频
- (IBAction)playVideo:(id)sender {
AVPlayerViewController * vc = [[AVPlayerViewController alloc] init];
NSString * path = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"MP4"];
NSURL * url = [NSURL fileURLWithPath:path];
AVPlayerItem * item = [[AVPlayerItem alloc] initWithURL:url];
vc.player = [[AVPlayer alloc] initWithPlayerItem:item];
vc.player = [AVPlayer playerWithURL:url];
vc.entersFullScreenWhenPlaybackBegins = YES;
vc.exitsFullScreenWhenPlaybackEnds = YES;
vc.videoGravity = AVLayerVideoGravityResizeAspect;
vc.view.bounds = CGRectMake(20, 20, 300, 160);
vc.view.center = self.view.center;
vc.view.translatesAutoresizingMaskIntoConstraints = YES;
[self addChildViewController:vc];
[self.view addSubview:vc.view];
[vc.player play];
}
下面的代码是解决全屏时默认横屏
思路也比较简单,既然全屏时只有手动改变设备方向才能使视频全屏,那么我们就在播放器全屏的时候用代码强制改变一下设备方向(真实设备此时可能依旧是竖屏状态)
static NSString * const VIDEO_CONTROLLER_CLASS_NAME_IOS8 = @"AVFullScreenViewController";
//AVFullScreenViewController是点击全屏按钮时系统 present 的控制器,我们可以通过[window.rootViewController presentedViewController]获取控制器的名字.
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
if ([[window.rootViewController presentedViewController] isKindOfClass:NSClassFromString(VIDEO_CONTROLLER_CLASS_NAME_IOS8)]) {
NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];
return UIInterfaceOrientationMaskPortrait;
} else {
NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];
return UIInterfaceOrientationMaskPortrait;
}
}
网友评论