iOS DeveloperiOS开发

AVPlayer封装

2019-03-19  本文已影响73人  taobingzhi

说明

基于AVPlayer和MVP模式封装的一个视频播放控制器,支持全屏,暂停播放,进度条拖动。

Demo地址

AVPlayer框架介绍

AVPlay既可以用来播放音频也可以用来播放视频,AVPlay在播放音频方面可以直接用来播放网络上的音频。在使用AVPlay的时候我们需要导入AVFoundation.framework框架,再引入头文件#import<AVFoundation/AVFoundation.h>。

主要包括下面几个类

1.AVPlayer:播放器类
2.AVPlayerItem:播放单元类,即一个播放源
3.AVPlayerLayer:播放界面

使用时,需要先根据NSURL生成一个播放源,[AVPlayerItem playerItemWithURL:],再根据这个播放源获得一个播放器对象,[AVPlayer playerWithPlayerItem:];,此时播放器已经准备完成,但还需要根据AVPlayer生成一个AVPlayerLayer,设置frame,再加入到superView.layer中,[AVPlayerLayer playerLayerWithPlayer:]; self.playerLayer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.width*0.6); [self.layer addSublayer:self.playerLayer];

此时一个简单的播放器就已经配置完成。

暂停播放

AVPlayer有一个rate属性,可以根据这个属性来判断当前是否在播放,rate == 0.f为暂停,反之视频播放。

AVPlayerItemStatus

可以对AVPlayerItem设置kvo,监听视频源是否可播放,系统给了三种状态,如下:

typedef NS_ENUM(NSInteger, AVPlayerItemStatus) {
    AVPlayerItemStatusUnknown,
    AVPlayerItemStatusReadyToPlay,
    AVPlayerItemStatusFailed
};

设置KVO监听:

[self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItemStatus status = [change[NSKeyValueChangeNewKey] intValue];
        if (status == AVPlayerItemStatusReadyToPlay) {
            isReadyToPlay = YES;
            [self.player play];
        }else{
            //预留
            isReadyToPlay = NO;
        }
        [self.controlView controlItemStatus:status playItem:object];
    }
}
全屏操作

Demo中给出的思路是:

1.首先将当前竖屏状态下的播放器的view的frame保存下来,方便退出全屏时,布局;
2.然后新建一个全屏展示View的控制器,重写该控制器的@property(nonatomic, readonly) UIInterfaceOrientation preferredInterfaceOrientationForPresentation NS_AVAILABLE_IOS(6_0) __TVOS_PROHIBITED;,强制让该控制器旋转;
3.将当前根控制器present到上述的全屏控制器,在completion:回调中,做个简单的动画过渡一下,然后再将承载AVPlayerLayer的view的frame改成横屏状态,然后再修改AVPlayerLayer的frame;

退出全屏:

1.将当前全屏控制器dismiss;
2.再dismiss的成功回调中,设置View的frame为进入全屏前保存的frame;
3.再将AVPlayerLayer的frame修改。

代码如下:

#pragma mark - 进入全屏和退出全屏的动画和present处理
- (void)enterFullScreen:(BOOL)rightOrLeft{
    playViewBeforeRect = _playerView.frame;
    playViewBeforeCenter = _playerView.center;
    
    TBZAVFullViewController *vc = [[TBZAVFullViewController alloc] init];
    vc.type = rightOrLeft;
    self.fullVC = vc;
    
    __weak TBZAVPlayerViewController *weakSelf = self;
    
    [self.navigationController presentViewController:vc animated:false completion:^{
        [UIView animateWithDuration:0.25 animations:^{
            weakSelf.playerView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
        } completion:^(BOOL finished) {
            [weakSelf.playerView enterFull];
            [weakSelf.fullVC.view addSubview:weakSelf.playerView];
            [UIApplication.sharedApplication.keyWindow insertSubview:UIApplication.sharedApplication.keyWindow.rootViewController.view belowSubview:vc.view.superview];
            
            self->isFull = YES;
        }];
    }];
}

- (void)exitFullScreen{
    __weak TBZAVPlayerViewController *weakSelf = self;
    [self.fullVC dismissViewControllerAnimated:false completion:^{
        [UIView animateWithDuration:0.25 animations:^{
            weakSelf.playerView.frame = self->playViewBeforeRect;
        } completion:^(BOOL finished) {
            [weakSelf.playerView exitFull];
            [weakSelf.view addSubview:weakSelf.playerView];
            
            self->isFull = NO;
        }];
    }];
}
播放进度

主要就是需要对AVPlayer添加监听,且注意需要释放该方法返回的对象。AVPlayerItem有两个属性,currentTime和duration,这两个对象都是CMTime类,可以用CMTimeGetSeconds(CMTime t);得到一个float指,秒数。也就是CMTimeGetSeconds(item.currentTime)可以得到当前播放到第几秒,CMTimeGetSeconds(item.duration)可以得到当前视频的总时长。

/*!
    @method         addPeriodicTimeObserverForInterval:queue:usingBlock:
    @abstract       Requests invocation of a block during playback to report changing time.
    @param          interval
      The interval of invocation of the block during normal playback, according to progress of the current time of the player.
    @param          queue
      The serial queue onto which block should be enqueued.  If you pass NULL, the main queue (obtained using dispatch_get_main_queue()) will be used.  Passing a
      concurrent queue to this method will result in undefined behavior.
    @param          block
      The block to be invoked periodically.
    @result
      An object conforming to the NSObject protocol.  You must retain this returned value as long as you want the time observer to be invoked by the player.
      Pass this object to -removeTimeObserver: to cancel time observation.
    @discussion     The block is invoked periodically at the interval specified, interpreted according to the timeline of the current item.
                    The block is also invoked whenever time jumps and whenever playback starts or stops.
                    If the interval corresponds to a very short interval in real time, the player may invoke the block less frequently
                    than requested. Even so, the player will invoke the block sufficiently often for the client to update indications
                    of the current time appropriately in its end-user interface.
                    Each call to -addPeriodicTimeObserverForInterval:queue:usingBlock: should be paired with a corresponding call to -removeTimeObserver:.
                    Releasing the observer object without a call to -removeTimeObserver: will result in undefined behavior.
*/
- (id)addPeriodicTimeObserverForInterval:(CMTime)interval queue:(nullable dispatch_queue_t)queue usingBlock:(void (^)(CMTime time))block;

/*!
    @method         removeTimeObserver:
    @abstract       Cancels a previously registered time observer.
    @param          observer
      An object returned by a previous call to -addPeriodicTimeObserverForInterval:queue:usingBlock: or -addBoundaryTimeObserverForTimes:queue:usingBlock:.
    @discussion     Upon return, the caller is guaranteed that no new time observer blocks will begin executing.  Depending on the calling thread and the queue
                    used to add the time observer, an in-flight block may continue to execute after this method returns.  You can guarantee synchronous time 
                    observer removal by enqueuing the call to -removeTimeObserver: on that queue.  Alternatively, call dispatch_sync(queue, ^{}) after
                    -removeTimeObserver: to wait for any in-flight blocks to finish executing.
                    -removeTimeObserver: should be used to explicitly cancel each time observer added using -addPeriodicTimeObserverForInterval:queue:usingBlock:
                    and -addBoundaryTimeObserverForTimes:queue:usingBlock:.
*/
- (void)removeTimeObserver:(id)observer;

- (id)addPeriodicTimeObserverForInterval:(CMTime)interval queue:(nullable dispatch_queue_t)queue usingBlock:(void (^)(CMTime time))block;其实就是一个Timer,每隔1秒执行block,可以设置常驻子线程,如果设为NULL,就是在主线程。
主要使用如下:

    __weak AVPlayer *weakAVPlayer = self.player;
    __weak TBZAVPlayerView *weakSelf = self;
    //监听播放进度,需要再destory方法中,释放timeObserve
    self.timeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(1, NSEC_PER_SEC) queue:NULL usingBlock:^(CMTime time) {
        CGFloat progress = CMTimeGetSeconds(weakAVPlayer.currentItem.currentTime) / CMTimeGetSeconds(weakAVPlayer.currentItem.duration);
        if (progress == 1.0f) {
            //视频播放完毕
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(playEnd)]) {
                [weakSelf.delegate playEnd];
            }
        }else{
            [weakSelf.controlView controlPlayItem:weakAVPlayer.currentItem];
        }
    }];

- (void)destroy{
    if (self.player || self.playerItem || self.playerLayer) {
        [self.player pause];
        if (self.timeObserver) {
            [self.player removeTimeObserver:self.timeObserver];
        }
        [self.playerItem removeObserver:self forKeyPath:@"status"];
        self.playerItem = nil;
        self.player = nil;
        [self.playerLayer removeFromSuperlayer];
    }
}

总结

1.当视频源切换了之后,需要将当前视频源添加的监听都remove掉,重新给新的视频源添加监听;
2.全屏跟退出全屏,主要是注意AVPlayerLayer的布局,不会跟着superLayer的变动而变动,需要手动再设置一遍;

具体可以结合Demo来看。

Demo下载


觉得有用,请帮忙点亮红心


Better Late Than Never!
努力是为了当机会来临时不会错失机会。
共勉!

上一篇下一篇

猜你喜欢

热点阅读