美文网首页iOS技术资料iOS Developer
AVPlayer工具栏以及画中画的自定义实现

AVPlayer工具栏以及画中画的自定义实现

作者: anjohnlv | 来源:发表于2017-08-24 10:25 被阅读718次

    AVPlayerViewController使用方便但不够灵活。
    搜索引擎了半天并没有找到自定义工具栏的方法。于是老老实实自己实现。

    工具栏的自定义

    基于AVplayer,自定义UIView,用于Player以及工具栏的显示

    @interface WKPlayerView : UIView
    
    @property(nonatomic, strong)AVPlayer *player;
    @property(nonatomic, strong)AVPlayerLayer *playerLayer;
    @property(nonatomic, strong)UIControl *contentView;//用于自定义工具栏,手势事件等。
    
    @end
    

    在这里,我删除了具体的界面布局代码。用户期望的自定义界面或事件都在contentView上实现即可。
    实现方式:

    _contentView = [UIControl new];
    [self addSubview:_contentView];
    [_contentView mas_makeConstraints:^(MASConstraintMaker *make){
        make.size.equalTo(self);
        make.center.equalTo(self);
    }];
    
    _player = [AVPlayer playerWithURL:[NSURL URLWithString:URLString]];
    _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    [_playerLayer setVideoGravity:AVLayerVideoGravityResizeAspect];
    //将playerLayer添加到contentView下,以免contentView的事件被挡住。
    [self.layer insertSublayer:_playerLayer below:_contentView.layer];
    [_player play];
    

    界面部分就完成了。

    播放的自定义

    播放过程中,我们可能会有播放、暂停、跳转、获取进度、缓冲等等事件。AVPlayer提供了
    - (void)play;
    - (void)pause;
    - (void)seekToTime:(CMTime)time;(还有更多实现)
    - (CMTime)currentTime;
    等api,可以灵活的根据需求自定义实现。

    在这里记录一下观察播放进度和缓冲进度的方法:
    播放进度:- addPeriodicTimeObserverForInterval:queue:usingBlock:

    - (void)addPeriodicTimeObserver {
        // Invoke callback every half second
        CMTime interval = CMTimeMakeWithSeconds(0.5, NSEC_PER_SEC);
        // Queue on which to invoke the callback
        dispatch_queue_t mainQueue = dispatch_get_main_queue();
        // Add time observer
        self.timeObserverToken =
            [self.player addPeriodicTimeObserverForInterval:interval
                                                      queue:mainQueue
                                                 usingBlock:^(CMTime time) {
                                                     // Use weak reference to self
                                                     // Update player transport UI
                                                 }];
    }
    

    注意:添加了timeObserver后,不使用的时候记得调用- removeTimeObserver:,否则会占用大量内存。

    缓冲进度:
    当网络出现问题时,AVPlayer将会自动暂停,所以当缓冲好了之后,我们必须手动调用- (void)play;
    AVPlayerItem是使用KVO模式观察状态,所以我们可以通过观察 loadedTimeRanges 获取缓冲进度:

    [self.player.currentItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];// 监听loadedTimeRanges属性
    
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
        if ([keyPath isEqualToString:@"loadedTimeRanges"]){
            NSTimeInterval timeInterval = [self availableDuration];// 缓冲进度
            //todo:刷新缓冲进度条、播放等逻辑 
        }
    }
    

    更多的功能请参考API

    画中画的实现

    在使用AVPlayerViewController时,只需要简单设置allowsPictureInPicturePlayback,即可实现画中画功能。
    那我们的自定义播放器呢?
    实现方式我参考了https://stackoverflow.com/questions/32667090/how-to-display-avpictureinpicturecontroller
    翻译一下:
    1、首先我们在Capabilities里的Background Modes设置Audio, AirPlay and Picture in Picture,如图

    设置背景模块

    2、在Appdelegate里设置

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    

    3、在AVPlayer初始化完成后添加如下代码

    -(void)play:(NSString *)URLString {
        self.player = [AVPlayer playerWithURL:[NSURL URLWithString:URLString]];
        self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
        [self.playerLayer setVideoGravity:AVLayerVideoGravityResizeAspect];
        [self.layer insertSublayer:self.playerLayer below:_contentView.layer];
        [_player play];
        //添加画中画相关代码
        [self setupSuport];
    }
    
    -(void)setupSuport {
        if([AVPictureInPictureController isPictureInPictureSupported]) {
            //属性变量@property(nonatomic, strong)AVPictureInPictureController *AVPictureInPictureController;
            _AVPictureInPictureController =  [[AVPictureInPictureController alloc] initWithPlayerLayer:self.playerLayer];
            _AVPictureInPictureController.delegate = self;
        } else {
            // not supported PIP start button desable here
        }
    }
    

    4、自定义启动画中画按钮事件

    if (_AVPictureInPictureController.pictureInPictureActive) {
        [_AVPictureInPictureController stopPictureInPicture];
    } else {
        [_AVPictureInPictureController startPictureInPicture];
    }
    

    到这就完成了。
    你还可以实现delegate,以自定义更多功能。

    - (void)pictureInPictureController:(AVPictureInPictureController *)pictureInPictureController restoreUserInterfaceForPictureInPictureStopWithCompletionHandler:(void (^)(BOOL restored))completionHandler;
    - (void)pictureInPictureControllerDidStopPictureInPicture:(AVPictureInPictureController *)pictureInPictureController;
    - (void)pictureInPictureControllerDidStartPictureInPicture:(AVPictureInPictureController *)pictureInPictureController;
    - (void)pictureInPictureControllerWillStopPictureInPicture:(AVPictureInPictureController *)pictureInPictureController;
    - (void)pictureInPictureController:(AVPictureInPictureController *)pictureInPictureController failedToStartPictureInPictureWithError:(NSError *)error;
    - (void)pictureInPictureControllerWillStartPictureInPicture:(AVPictureInPictureController *)pictureInPictureController;
    

    到这里,一个自定义播放器就基本上完成了。

    相关文章

      网友评论

        本文标题:AVPlayer工具栏以及画中画的自定义实现

        本文链接:https://www.haomeiwen.com/subject/anpkdxtx.html