AVPlayer封裝

說明

基于AVPlayer和MVP模式封裝的一個視頻播放控制器,支持全屏,暫停播放,進(jìn)度條拖動。

Demo地址

AVPlayer框架介紹

AVPlay既可以用來播放音頻也可以用來播放視頻,AVPlay在播放音頻方面可以直接用來播放網(wǎng)絡(luò)上的音頻。在使用AVPlay的時候我們需要導(dǎo)入AVFoundation.framework框架,再引入頭文件#import<AVFoundation/AVFoundation.h>。

主要包括下面幾個類

1.AVPlayer:播放器類
2.AVPlayerItem:播放單元類,即一個播放源
3.AVPlayerLayer:播放界面

使用時,需要先根據(jù)NSURL生成一個播放源,[AVPlayerItem playerItemWithURL:],再根據(jù)這個播放源獲得一個播放器對象,[AVPlayer playerWithPlayerItem:];,此時播放器已經(jīng)準(zhǔn)備完成,但還需要根據(jù)AVPlayer生成一個AVPlayerLayer,設(shè)置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];

此時一個簡單的播放器就已經(jīng)配置完成。

暫停播放

AVPlayer有一個rate屬性,可以根據(jù)這個屬性來判斷當(dāng)前是否在播放,rate == 0.f為暫停,反之視頻播放。

AVPlayerItemStatus

可以對AVPlayerItem設(shè)置kvo,監(jiān)聽視頻源是否可播放,系統(tǒng)給了三種狀態(tài),如下:

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

設(shè)置KVO監(jiān)聽:

[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{
            //預(yù)留
            isReadyToPlay = NO;
        }
        [self.controlView controlItemStatus:status playItem:object];
    }
}
全屏操作

Demo中給出的思路是:

1.首先將當(dāng)前豎屏狀態(tài)下的播放器的view的frame保存下來,方便退出全屏?xí)r,布局;
2.然后新建一個全屏展示View的控制器,重寫該控制器的@property(nonatomic, readonly) UIInterfaceOrientation preferredInterfaceOrientationForPresentation NS_AVAILABLE_IOS(6_0) __TVOS_PROHIBITED;,強(qiáng)制讓該控制器旋轉(zhuǎn);
3.將當(dāng)前根控制器present到上述的全屏控制器,在completion:回調(diào)中,做個簡單的動畫過渡一下,然后再將承載AVPlayerLayer的view的frame改成橫屏狀態(tài),然后再修改AVPlayerLayer的frame;

退出全屏:

1.將當(dāng)前全屏控制器dismiss;
2.再dismiss的成功回調(diào)中,設(shè)置View的frame為進(jìn)入全屏前保存的frame;
3.再將AVPlayerLayer的frame修改。

代碼如下:

#pragma mark - 進(jìn)入全屏和退出全屏的動畫和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;
        }];
    }];
}
播放進(jìn)度

主要就是需要對AVPlayer添加監(jiān)聽,且注意需要釋放該方法返回的對象。AVPlayerItem有兩個屬性,currentTime和duration,這兩個對象都是CMTime類,可以用CMTimeGetSeconds(CMTime t);得到一個float指,秒數(shù)。也就是CMTimeGetSeconds(item.currentTime)可以得到當(dāng)前播放到第幾秒,CMTimeGetSeconds(item.duration)可以得到當(dāng)前視頻的總時長。

/*!
    @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;其實(shí)就是一個Timer,每隔1秒執(zhí)行block,可以設(shè)置常駐子線程,如果設(shè)為NULL,就是在主線程。
主要使用如下:

    __weak AVPlayer *weakAVPlayer = self.player;
    __weak TBZAVPlayerView *weakSelf = self;
    //監(jiān)聽播放進(jìn)度,需要再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];
    }
}

總結(jié)

1.當(dāng)視頻源切換了之后,需要將當(dāng)前視頻源添加的監(jiān)聽都remove掉,重新給新的視頻源添加監(jiān)聽;
2.全屏跟退出全屏,主要是注意AVPlayerLayer的布局,不會跟著superLayer的變動而變動,需要手動再設(shè)置一遍;

具體可以結(jié)合Demo來看。

Demo下載


覺得有用,請幫忙點(diǎn)亮紅心


Better Late Than Never!
努力是為了當(dāng)機(jī)會來臨時不會錯失機(jī)會。
共勉!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,663評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,125評論 3 414
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,506評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,614評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,402評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,934評論 1 321
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,021評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,168評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,690評論 1 333
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,596評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,784評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,288評論 5 357
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,027評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,404評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,662評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,398評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,743評論 2 370