AVPlayer封裝

說明

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

Demo地址

AVPlayer框架介紹

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

主要包括下面幾個(gè)類

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

使用時(shí)渺氧,需要先根據(jù)NSURL生成一個(gè)播放源棱烂,[AVPlayerItem playerItemWithURL:],再根據(jù)這個(gè)播放源獲得一個(gè)播放器對(duì)象阶女,[AVPlayer playerWithPlayerItem:];颊糜,此時(shí)播放器已經(jīng)準(zhǔn)備完成,但還需要根據(jù)AVPlayer生成一個(gè)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];

此時(shí)一個(gè)簡(jiǎn)單的播放器就已經(jīng)配置完成憔杨。

暫停播放

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

AVPlayerItemStatus

可以對(duì)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.然后新建一個(gè)全屏展示View的控制器樊拓,重寫該控制器的@property(nonatomic, readonly) UIInterfaceOrientation preferredInterfaceOrientationForPresentation NS_AVAILABLE_IOS(6_0) __TVOS_PROHIBITED;,強(qiáng)制讓該控制器旋轉(zhuǎn)塘慕;
3.將當(dāng)前根控制器present到上述的全屏控制器筋夏,在completion:回調(diào)中,做個(gè)簡(jiǎn)單的動(dòng)畫過渡一下图呢,然后再將承載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)入全屏和退出全屏的動(dòng)畫和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)度

主要就是需要對(duì)AVPlayer添加監(jiān)聽稚瘾,且注意需要釋放該方法返回的對(duì)象牡昆。AVPlayerItem有兩個(gè)屬性姚炕,currentTime和duration,這兩個(gè)對(duì)象都是CMTime類丢烘,可以用CMTimeGetSeconds(CMTime t);得到一個(gè)float指柱宦,秒數(shù)。也就是CMTimeGetSeconds(item.currentTime)可以得到當(dāng)前播放到第幾秒播瞳,CMTimeGetSeconds(item.duration)可以得到當(dāng)前視頻的總時(shí)長(zhǎ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í)就是一個(gè)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的布局驯击,不會(huì)跟著superLayer的變動(dòng)而變動(dòng),需要手動(dòng)再設(shè)置一遍耐亏;

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

Demo下載


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


Better Late Than Never!
努力是為了當(dāng)機(jī)會(huì)來臨時(shí)不會(huì)錯(cuò)失機(jī)會(huì)广辰。
共勉碟贾!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末币喧,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子袱耽,更是在濱河造成了極大的恐慌杀餐,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,948評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件朱巨,死亡現(xiàn)場(chǎng)離奇詭異史翘,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)冀续,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,371評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門琼讽,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人洪唐,你說我怎么就攤上這事钻蹬。” “怎么了凭需?”我有些...
    開封第一講書人閱讀 157,490評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵问欠,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我粒蜈,道長(zhǎng)顺献,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,521評(píng)論 1 284
  • 正文 為了忘掉前任枯怖,我火速辦了婚禮注整,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘度硝。我一直安慰自己肿轨,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,627評(píng)論 6 386
  • 文/花漫 我一把揭開白布蕊程。 她就那樣靜靜地躺著椒袍,像睡著了一般。 火紅的嫁衣襯著肌膚如雪存捺。 梳的紋絲不亂的頭發(fā)上槐沼,一...
    開封第一講書人閱讀 49,842評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音捌治,去河邊找鬼岗钩。 笑死,一個(gè)胖子當(dāng)著我的面吹牛肖油,可吹牛的內(nèi)容都是我干的兼吓。 我是一名探鬼主播,決...
    沈念sama閱讀 38,997評(píng)論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼森枪,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼视搏!你這毒婦竟也來了审孽?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,741評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤浑娜,失蹤者是張志新(化名)和其女友劉穎佑力,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體筋遭,經(jīng)...
    沈念sama閱讀 44,203評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡打颤,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,534評(píng)論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了漓滔。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片编饺。...
    茶點(diǎn)故事閱讀 38,673評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖响驴,靈堂內(nèi)的尸體忽然破棺而出透且,到底是詐尸還是另有隱情,我是刑警寧澤豁鲤,帶...
    沈念sama閱讀 34,339評(píng)論 4 330
  • 正文 年R本政府宣布秽誊,位于F島的核電站,受9級(jí)特大地震影響畅形,放射性物質(zhì)發(fā)生泄漏养距。R本人自食惡果不足惜诉探,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,955評(píng)論 3 313
  • 文/蒙蒙 一日熬、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧肾胯,春花似錦竖席、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,770評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至艳馒,卻和暖如春憎亚,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背弄慰。 一陣腳步聲響...
    開封第一講書人閱讀 32,000評(píng)論 1 266
  • 我被黑心中介騙來泰國(guó)打工第美, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人陆爽。 一個(gè)月前我還...
    沈念sama閱讀 46,394評(píng)論 2 360
  • 正文 我出身青樓什往,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親慌闭。 傳聞我的和親對(duì)象是個(gè)殘疾皇子别威,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,562評(píng)論 2 349