视频播放avplayer

-(void)setupUI{
//创建播放器层
AVPlayerLayer *playerLayer=[AVPlayerLayer playerLayerWithPlayer:self.player];
playerLayer.frame=aview.frame;
playerLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;//视频填充模式
[aview.layer addSublayer:playerLayer];
}

-(AVPlayer *)player{
if (!_player) {
AVPlayerItem *playerItem=[self getPlayItem:0];
_player=[AVPlayer playerWithPlayerItem:playerItem];
[self addProgressObserver];
[self addObserverToPlayerItem:playerItem];
[self.player play];
}
return _player;
}

-(AVPlayerItem *)getPlayItem:(int)videoIndex{
// NSString *urlStr=[NSString stringWithFormat:@"colgate.mp4",@""];

NSString *path = [[NSBundle mainBundle] pathForResource:@"colgate.mp4" ofType:nil];
path =[path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL fileURLWithPath:path];
AVPlayerItem *playerItem=[AVPlayerItem playerItemWithURL:url];
return playerItem;

}

pragma mark - 通知

-(void)addNotification{
//给AVPlayerItem添加播放完成通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:)name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
}

-(void)removeNotification{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)playbackFinished:(NSNotification *)notification{
NSLog(@"视频播放完成.");
}

pragma mark - 监控

-(void)addProgressObserver{
AVPlayerItem *playerItem=self.player.currentItem;
//UIProgressView *progress=self.progress;
//这里设置每秒执行一次
[self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue()usingBlock:^(CMTime time) {
float current=CMTimeGetSeconds(time);
float total=CMTimeGetSeconds([playerItem duration]);
NSLog(@"当前已经播放%.2fs.",current);
if (current) {
//[progress setProgress:(current/total) animated:YES];
}
}];
}

-(void)addObserverToPlayerItem:(AVPlayerItem *)playerItem{
//监控状态属性,注意AVPlayer也有一个status属性,通过监控它的status也可以获得播放状态
[playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
//监控网络加载情况属性
[playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNewcontext:nil];
}
-(void)removeObserverFromPlayerItem:(AVPlayerItem *)playerItem{
[playerItem removeObserver:self forKeyPath:@"status"];
[playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
AVPlayerItem *playerItem=object;
if ([keyPath isEqualToString:@"status"]) {
AVPlayerStatus status= [[change objectForKey:@"new"] intValue];
if(status==AVPlayerStatusReadyToPlay){
NSLog(@"正在播放...,视频总长度:%.2f",CMTimeGetSeconds(playerItem.duration));
}
}else if([keyPath isEqualToString:@"loadedTimeRanges"]){
NSArray *array=playerItem.loadedTimeRanges;
CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];//本次缓冲时间范围
float startSeconds = CMTimeGetSeconds(timeRange.start);
float durationSeconds = CMTimeGetSeconds(timeRange.duration);
NSTimeInterval totalBuffer = startSeconds + durationSeconds;//缓冲总长度
NSLog(@"共缓冲:%.2f",totalBuffer);
//
}
}
//设置方向
-(void)toOrientation:(UIInterfaceOrientation)orientation{
//获取到当前状态条的方向
UIInterfaceOrientation currentOrientation = [UIApplication sharedApplication].statusBarOrientation;
//判断如果当前方向和要旋转的方向一致,那么不做任何操作
if (currentOrientation == orientation) {
return;
}
//根据要旋转的方向,使用Masonry重新修改限制
if (orientation ==UIInterfaceOrientationPortrait) {
[aview mas_remakeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.view).with.offset(40);
make.left.equalTo(self.view);
make.right.equalTo(self.view);
make.height.equalTo(200);
}];
}else{
//这个地方加判断是为了从全屏的一侧,直接到全屏的另一侧不用修改限制,否则会出错;
if (currentOrientation ==UIInterfaceOrientationPortrait) {
[aview mas_remakeConstraints:^(MASConstraintMaker *make) {
make.width.equalTo(@(kScreenWidth));
make.height.equalTo(@(kScreenHeight));
make.center.equalTo(aview.superview);
}];
}
}
//iOS6.0之后,设置状态条的方法能使用的前提是shouldAutorotate为NO,也就是说这个视图控制器内,旋转要关掉;
//也就是说在实现这个方法的时候-(BOOL)shouldAutorotate返回值要为NO
//[[UIApplication sharedApplication]setStatusBarOrientation:orientation animated:NO];
[[UIApplication sharedApplication] setStatusBarOrientation:orientation animated:NO];
//获取旋转状态条需要的时间:
CGFloat duration = [UIApplication sharedApplication].statusBarOrientation;
[UIView beginAnimations:nil context:nil];
//更改了状态条的方向,但是设备方向UIInterfaceOrientation还是正方向的,这就要设置给你播放视频的视图的方向设置旋转
//给你的播放视频的view视图设置旋转
aview.transform = [self getOrientation];
[UIView setAnimationDuration:duration];
//开始旋转
[UIView commitAnimations];
}
//根据想要旋转的方向来设置旋转
-(CGAffineTransform)getOrientation{
//状态条的方向已经设置过,所以这个就是你想要旋转的方向
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
//根据要进行旋转的方向来计算旋转的角度
if (orientation ==UIInterfaceOrientationPortrait) {
return CGAffineTransformIdentity;
}else if (orientation ==UIInterfaceOrientationLandscapeLeft){
return CGAffineTransformMakeRotation(-M_PI_2);
}else if(orientation ==UIInterfaceOrientationLandscapeRight){
return CGAffineTransformMakeRotation(M_PI_2);
}
return CGAffineTransformIdentity;
}

-(BOOL)shouldAutorotate{//iOS6.0之后,要想让状态条可以旋转,必须设置视图不能自动旋转
return NO;
}

你可能感兴趣的:(视频播放avplayer)