視頻播放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;
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容