自己在看到同事使用AVPlayer就想学习下,在网上看到很多这类资料,照着写啦一个简单的Demo,也给以后的自己看,用到也不用再苦苦寻找。这个简单Demo还有待继续开发和优化,先把基本内容展示下;
在使用AVPlayer过程中发现,这个控件苹果官方设置有自动布局大小,所以在使用时,会根据你设置的宽高去适配它自己的宽高,这样就造成不是你想要的界面效果,我自己研究下,系统AVPlayer布局宽高比应该是320:180,不知道对不对,你们也可以自己看下,根据这个比例,我在界面也按照这个比例去设置视频播放的区域,代码如下:
_playViewHeight = 180*self.view.bounds.size.width/320;
PlayView *playView = [[PlayView alloc]init];
playView.bounds = CGRectMake(0, 0, self.view.bounds.size.width, _playViewHeight);
playView.center = self.view.center;
[playView.fullButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
//本地视频
// NSString *path = [[NSBundle mainBundle] pathForResource:@"环保小视频.mp4" ofType:nil];
// NSURL *url = [NSURL fileURLWithPath:path];
//网络视频
NSURL *url = [NSURL URLWithString:URL];
[playView updateVideoItem:url];
[self.view addSubview:playView];
self.playView = playView;
在第一个界面,我强制让它只支持竖屏,全屏是present到另外一个界面,退出全屏是dismiss到前面界面,尺寸都要在跳转前设置好,代码如下:
- (void)buttonClick:(UIButton *)sender{
sender.selected = !sender.selected;
FullViewController *fullVC = [[FullViewController alloc]init];
fullVC.playView = self.playView;
__weak ViewController *vc = self;
if (sender.isSelected) {
[self presentViewController:fullVC animated:YES completion:^{
vc.playView.frame = fullVC.view.bounds;
[fullVC.view addSubview:vc.playView];
}];
}
fullVC.dismissAction = ^(CGSize viewSize){
vc.playView.bounds = CGRectMake(0, 0, viewSize.height, _playViewHeight);
vc.playView.center = CGPointMake(viewSize.height/2, viewSize.width/2);
[vc.view addSubview:vc.playView];
};
}
还有控制进度,暂停开始播放等功能,想了解可以看我的demo,播放进度和时间是通过定时器实时获取的,播放进度和播放时间代码如下:
//计算播放进度和时间
- (void)calculateProgress{
CGFloat currentTime = CMTimeGetSeconds(self.playerItem.currentTime);
CGFloat totalTime = CMTimeGetSeconds(self.playerItem.duration);
CGFloat value = currentTime/totalTime;
self.progressSlider.value = value;
NSString *currentTimeStr = [self calculateTimeWithTime:currentTime];
NSString *totalTimeStr = [self calculateTimeWithTime:totalTime];
self.timeLabel.text = [NSString stringWithFormat:@"%@/%@",currentTimeStr,totalTimeStr];
}
暂时简单写到这里,还有别的小功能,想了解的可以下载我的小Demo。
网友评论