iOS多播放器封裝

今年在做直播業(yè)務(wù)的時候遇到一些問題,就是在一個套播放器UI中需要多種不同的播放器(AVPlayer、IJKPlayer、AliPlayer)支持,根據(jù)ABTest開關(guān)來切換具體使用哪種播放器,并且還要對播放器進(jìn)行日志統(tǒng)計。
首先可以想到的是需要對不同的播放器封裝一個統(tǒng)一的接口,對于UI來講,不需要關(guān)系當(dāng)前操控的是哪個播放器。

多播放器架構(gòu).jpg

其中player protocal是個關(guān)鍵

@protocol VideoPlaybackProtocal <NSObject>
@property (nonatomic, assign, setter=setDelegate:) id<LivePlaybackEventListener> delegate;

-(void)addPlaybackEventListener:(id<LivePlaybackEventListener>)listener;
-(void)removePlaybackEventListener:(id<LivePlaybackEventListener>)listener;

@property (nonatomic, strong, readonly) UIView * view;
@property (nonatomic, assign, readonly) CMTime currentPlaybackTime;
@property (nonatomic, assign, readonly) CMTime duration;
@property (nonatomic, assign, readonly) NSURL *currentPlayUrl;
@property (nonatomic, assign, readonly) BOOL supportsRTMP;

- (void)stopDueToLiveDidEnd;
- (void)resume;
- (void)pause;
- (void)replay;
- (void)reload;
- (void)startPlayingWithPlayInfo:(NSURL*)url;
- (void)shutdown;
- (void)seekToProgress:(double)progress event:(PlayerEvent)event;
- (BOOL)isPlaying;
@end

然后三個播放器對這個接口進(jìn)行各自的實(shí)現(xiàn)。這樣對于ViewController來說播放器就是一個id<VideoPlaybackProtocal>,對播放器進(jìn)行暫停播放各種操作就可以。打算用哪個播放器,就把id<VideoPlaybackProtocal>實(shí)例化成哪個播放器的實(shí)現(xiàn),輕松又簡單。

其中這里的Listener是一個delegate,當(dāng)播放器出現(xiàn)播放完成、播放錯誤等事件時,Listener會對注冊了Listener的對象進(jìn)行廣播,目前需要注冊的是ViewController和Logger,UI收到廣播來進(jìn)行圖形界面的變化,Logger則負(fù)責(zé)將事件統(tǒng)計上傳到日志服務(wù)器當(dāng)中。這個廣播器通過一個NSHashTable * _listeners;來保證注冊了廣播的observe為弱引用,然后通過遍歷observe來進(jìn)行delegate調(diào)用,例如:

- (void)videoPlayerController:(id< VideoPlaybackProtocal >)playerController didFailWithError:(NSError *)error playerLog:(NSDictionary *)playerLog
{
    [self _enumerateListeners:^(id listener, NSUInteger idx) {
        if ([listener respondsToSelector:_cmd]) {
            [listener videoPlayerController:playerController didFailWithError:error playerLog:playerLog];
        }
    }];
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容