【iOS】教你用ZFPlayer+KTVHTTPCache搭建緩存,預(yù)加載的播放器

Demo演示的功能

提示:文末有相關(guān)的Demo下載鏈接

  • ZFPlayer的列表播放
  • 使用KTVHTTPCache實(shí)現(xiàn)緩存(播放過的視頻無需再下載)
  • 使用KTVHTTPCache實(shí)現(xiàn)預(yù)加載(可以實(shí)現(xiàn)秒播)
  • 自定義轉(zhuǎn)場(chǎng)動(dòng)畫(實(shí)現(xiàn)無縫銜接的播放效果)
  • 瀑布流頁面(雙排列表展示,以及轉(zhuǎn)場(chǎng)動(dòng)畫)

gif演示:


playerDemo.gif

一、緩存+預(yù)加載功能

1、播放器mgr核心代碼

mgr實(shí)現(xiàn)ZFPlayerMediaPlayback協(xié)議,然后在初始化時(shí),開啟本地服務(wù)器

+ (void)initialize
{
    [KTVHTTPCache logSetConsoleLogEnable:NO];
    NSError *error = nil;
    [KTVHTTPCache proxyStart:&error];
    if (error) {
        NSLog(@"Proxy Start Failure, %@", error);
    }
    [KTVHTTPCache encodeSetURLConverter:^NSURL *(NSURL *URL) {
//        NSLog(@"URL Filter reviced URL : %@", URL);
        return URL;
    }];
    [KTVHTTPCache downloadSetUnacceptableContentTypeDisposer:^BOOL(NSURL *URL, NSString *contentType) {
        return NO;
    }];
    // 設(shè)置緩存最大容量
    [KTVHTTPCache cacheSetMaxCacheLength:1024 * 1024 * 1024];
}

設(shè)置assetURL時(shí),設(shè)置KTVHTTpCache為中間服務(wù)器,若該資源已緩存完畢,就無需代理,這個(gè)判斷可以使已緩存的視頻播放的更快

- (void)setAssetURL:(NSURL *)assetURL {
    if (self.player) [self stop];
    // 如果有緩存,直接取本地緩存
    NSURL *url = [KTVHTTPCache cacheCompleteFileURLWithURL:assetURL];
    if (url) {
        _assetURL = url;
    }else {
        // 設(shè)置代理
        _assetURL = [KTVHTTPCache proxyURLWithOriginalURL:assetURL];
    }
    [self prepareToPlay];
}

2、播放器Player核心代碼

創(chuàng)建playableProtocol,方便數(shù)據(jù)管理

/// 只有實(shí)現(xiàn)該協(xié)議的模型才能預(yù)加載
@protocol XSTPlayable <NSObject>
/// string 視頻鏈接
@property (nonatomic, copy) NSString *video_url;
@end

核心播放器為ZFPlayerController,為了方便管理,我們創(chuàng)建一個(gè)中間類包裹ZFPlayerController,且增加可以設(shè)置的預(yù)加載屬性

@interface MPPlayerController : NSObject

// 預(yù)加載上幾條
@property (nonatomic, assign) NSUInteger preLoadNum;
/// 預(yù)加載下幾條
@property (nonatomic, assign) NSUInteger nextLoadNum;
/// 預(yù)加載的的百分比,默認(rèn)10%
@property (nonatomic, assign) double preloadPrecent;
/// 設(shè)置playableAssets后,馬上預(yù)加載的條數(shù)
@property (nonatomic, assign) NSUInteger initPreloadNum;
/// set之后,先預(yù)加載幾個(gè)
@property (nonatomic, copy) NSArray<id<XSTPlayable>> *playableArray;
....

3、預(yù)加載核心代碼

預(yù)加載的時(shí)機(jī)是當(dāng)前視頻可以播放了,才進(jìn)行預(yù)加載

- (void)playTheIndexPath:(NSIndexPath *)indexPath playable: (id<XSTPlayable>)playable
{
    // 播放前,先停止所有的預(yù)加載任務(wù)
    [self cancelAllPreload];
    _currentPlayable = playable;
    [self.player playTheIndexPath:indexPath assetURL:[NSURL URLWithString:playable.video_url] scrollToTop:NO];
    __weak typeof(self) weakSelf = self;
    self.playerReadyToPlay = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSURL * _Nonnull assetURL) {
        [weakSelf preload: playable];
    };
}

預(yù)加載的規(guī)則是預(yù)加載當(dāng)前視頻的上2個(gè),和下2個(gè)視頻,逐個(gè)開啟預(yù)加載,視頻預(yù)加載(核心類KTVHCDataLoader)到10%就停止,然后開始下一個(gè)視頻的預(yù)加載。這里要注意異步線程的操作,要加鎖處理

/// 根據(jù)傳入的模型,預(yù)加載上幾個(gè),下幾個(gè)的視頻
- (void)preload: (id<XSTPlayable>)resource
{
    if (self.playableArray.count <= 1)
        return;
    if (_nextLoadNum == 0 && _preLoadNum == 0)
        return;
    NSInteger start = [self.playableArray indexOfObject:resource];
    if (start == NSNotFound)
        return;
    [self cancelAllPreload];
    NSInteger index = 0;
    for (NSInteger i = start + 1; i < self.playableArray.count && index < _nextLoadNum; i++)
    {
        index += 1;
        id<XSTPlayable> model = self.playableArray[i];
        XSTPreLoaderModel *preModel = [self getPreloadModel: model.video_url];
        if (preModel) {
            @synchronized (self.preloadArr) {
                [self.preloadArr addObject: preModel];
            }
        }
    }
    index = 0;
    for (NSInteger i = start - 1; i >= 0 && index < _preLoadNum; i--)
    {
        index += 1;
        id<XSTPlayable> model = self.playableArray[i];
        XSTPreLoaderModel *preModel = [self getPreloadModel: model.video_url];
        if (preModel) {
            @synchronized (self.preloadArr) {
                [self.preloadArr addObject:preModel];
            }
        }
    }
    [self processLoader];
}
/// 取消所有的預(yù)加載
- (void)cancelAllPreload
{
    @synchronized (self.preloadArr) {
        if (self.preloadArr.count == 0)
        {
            return;
        }
        [self.preloadArr enumerateObjectsUsingBlock:^(XSTPreLoaderModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj.loader close];
        }];
        [self.preloadArr removeAllObjects];
    }
}

- (XSTPreLoaderModel *)getPreloadModel: (NSString *)urlStr
{
    if (!urlStr)
        return nil;
    // 判斷是否已在隊(duì)列中
    __block Boolean res = NO;
    @synchronized (self.preloadArr) {
        [self.preloadArr enumerateObjectsUsingBlock:^(XSTPreLoaderModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.url isEqualToString:urlStr])
            {
                res = YES;
                *stop = YES;
            }
        }];
    }
    if (res)
        return nil;
    NSURL *proxyUrl = [KTVHTTPCache proxyURLWithOriginalURL: [NSURL URLWithString:urlStr]];
    KTVHCDataCacheItem *item = [KTVHTTPCache cacheCacheItemWithURL:proxyUrl];
    double cachePrecent = 1.0 * item.cacheLength / item.totalLength;
    // 判斷緩存已經(jīng)超過10%了
    if (cachePrecent >= self.preloadPrecent)
        return nil;
    KTVHCDataRequest *req = [[KTVHCDataRequest alloc] initWithURL:proxyUrl headers:[NSDictionary dictionary]];
    KTVHCDataLoader *loader = [KTVHTTPCache cacheLoaderWithRequest:req];
    XSTPreLoaderModel *preModel = [[XSTPreLoaderModel alloc] initWithURL:urlStr loader:loader];
    return preModel;
}

- (void)processLoader
{
    @synchronized (self.preloadArr) {
        if (self.preloadArr.count == 0)
            return;
        XSTPreLoaderModel *model = self.preloadArr.firstObject;
        model.loader.delegate = self;
        [model.loader prepare];
    }
}

/// 根據(jù)loader,移除預(yù)加載任務(wù)
- (void)removePreloadTask: (KTVHCDataLoader *)loader
{
    @synchronized (self.preloadArr) {
        XSTPreLoaderModel *target = nil;
        for (XSTPreLoaderModel *model in self.preloadArr) {
            if ([model.loader isEqual:loader])
            {
                target = model;
                break;
            }
        }
        if (target)
            [self.preloadArr removeObject:target];
    }
}

// MARK: - KTVHCDataLoaderDelegate
- (void)ktv_loaderDidFinish:(KTVHCDataLoader *)loader
{
}
- (void)ktv_loader:(KTVHCDataLoader *)loader didFailWithError:(NSError *)error
{
    // 若預(yù)加載失敗的話,就直接移除任務(wù),開始下一個(gè)預(yù)加載任務(wù)
    [self removePreloadTask:loader];
    [self processLoader];
}
- (void)ktv_loader:(KTVHCDataLoader *)loader didChangeProgress:(double)progress
{
    if (progress >= self.preloadPrecent)
    {
        [loader close];
        [self removePreloadTask:loader];
        [self processLoader];
    }
}

二、無縫銜接轉(zhuǎn)場(chǎng)動(dòng)畫

這里我直接拿ZFPlayerDemo中的一個(gè)列表播放,一個(gè)抖音列表播放的例子進(jìn)行演示,不熟悉轉(zhuǎn)場(chǎng)動(dòng)畫的,建議自行先看看唐巧的https://blog.devtang.com/2016/03/13/iOS-transition-guide/了解,這里不多說,直接上核心代碼。

1、首先必須實(shí)現(xiàn)代理UINavigationControllerDelegate

@interface MPDetailViewController : UIViewController<UINavigationControllerDelegate>

2、傳遞player,startView,startImage等,并實(shí)現(xiàn)popback回調(diào)

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZFTableViewCell *cell = (ZFTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    NSIndexPath *currentIndexPath = [self.tableView indexPathForCell:cell];
    // 點(diǎn)擊的不是正在播放的cell,就先播放再跳轉(zhuǎn)
    if ([currentIndexPath compare:self.tableView.zf_playingIndexPath] != NSOrderedSame) {
        [self.player stopCurrentPlayingCell];
        self.tableView.zf_playingIndexPath = currentIndexPath;
        [self playTheVideoAtIndexPath:currentIndexPath scrollToTop:NO];
        [self.player.currentPlayerManager.view layoutIfNeeded];
    }
    self.tableView.zf_playingIndexPath = currentIndexPath;
    
    MPDetailViewController *vc = [[MPDetailViewController alloc] init];
    vc.player = self.player;
    vc.index = indexPath.row;
    vc.startImage = cell.coverImageView.image;
    vc.startView = cell.coverImageView;
    vc.dataSource = [self.playableArray mutableCopy];
    @weakify(self)
    vc.popbackBlock = ^{
        @strongify(self)
        [self.player updateScrollViewPlayerToCell];
        [self.player.currentPlayerManager play];
    };
    self.navigationController.delegate = vc;
    [self.navigationController pushViewController:vc animated:YES];
}

3、實(shí)現(xiàn)UIViewControllerAnimatedTransitioning協(xié)議

/// 用于視頻信息流的轉(zhuǎn)場(chǎng)動(dòng)畫
@interface MPTransition : NSObject<UIViewControllerAnimatedTransitioning>

/**
 初始化動(dòng)畫
 
 @param duration 動(dòng)畫時(shí)長
 @param startView 開始視圖
 @param startImage 開始圖片
 @param  player 播放器
 @param operation 動(dòng)畫形式
 @param completion 動(dòng)畫完成block
 @return 動(dòng)畫實(shí)例
 */
+ (instancetype)animationWithDuration:(NSTimeInterval)duration
                            startView:(UIView *)startView
                           startImage:(UIImage *)startImage
                               player: (MPPlayerController *)player
                            operation:(UINavigationControllerOperation)operation
                           completion:(void(^)(void))completion;

@end

4、分別實(shí)現(xiàn)push,pop的轉(zhuǎn)場(chǎng)動(dòng)畫

@interface MPTransition()

@property (nonatomic, strong) UIView *startView;
@property (nonatomic, strong) UIImage *startImage;
@property (nonatomic, assign) NSTimeInterval duration;
@property (nonatomic, strong) MPPlayerController *player;
@property (nonatomic, assign) UINavigationControllerOperation operation;
@property (nonatomic, assign) void(^completion)(void);
@property (nonatomic, strong) UIView *effectView;

@end

@implementation MPTransition

+ (instancetype)animationWithDuration:(NSTimeInterval)duration
                              startView:(UIView *)startView
                             startImage:(UIImage *)startImage
                                 player: (MPPlayerController *)player
                              operation:(UINavigationControllerOperation)operation
                             completion:(void(^)(void))completion
{
    MPTransition *animation = [MPTransition new];
    animation.player = player;
    animation.duration = duration;
    animation.startView = startView;
    animation.startImage = startImage;
    animation.operation = operation;
    animation.completion = completion;
    
    return animation;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    if (self.operation == UINavigationControllerOperationPush) {
        [self startPushAnimation: transitionContext];
    }else {
        [self startPopAnimation: transitionContext];
    }
}

- (void)startPushAnimation:(id<UIViewControllerContextTransitioning>)transitionContext
{
    // 獲取 fromView 和 toView
    UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
    UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    
    // 添加到動(dòng)畫容器視圖中
    [[transitionContext containerView] addSubview:fromView];
    [[transitionContext containerView] addSubview:toView];
    
    UIImageView *bgImgView = [[UIImageView alloc] initWithFrame:fromView.bounds];
    bgImgView.contentMode = UIViewContentModeScaleAspectFill;
    bgImgView.image = self.startImage;
    UIView *colorCover = [[UIView alloc] init];
    colorCover.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    colorCover.frame = fromView.bounds;
    [bgImgView addSubview:colorCover];
    [bgImgView addSubview:self.effectView];
    [[transitionContext containerView] addSubview:bgImgView];
    
    // 創(chuàng)建player容器
    CGRect winFrame = CGRectZero;
    if (self.startView) {
        winFrame = [self.startView convertRect:self.startView.bounds toView:nil];
    }
    
    UIImageView *playerContainer = [[UIImageView alloc] initWithFrame:winFrame];
    playerContainer.image = self.startImage;
    playerContainer.contentMode = UIViewContentModeScaleAspectFit;
    [[transitionContext containerView]  addSubview:playerContainer];
    if (self.player) {
        self.player.currentPlayerManager.scalingMode = self.player.videoFlowScalingMode;
        self.player.currentPlayerManager.view.backgroundColor = [UIColor clearColor];
        [self.player updateNoramlPlayerWithContainerView:playerContainer];
    }
    CGFloat bottomOffset = iPhoneX ? 83 : 0;
    NSTimeInterval duration = [self transitionDuration:transitionContext];
    CGRect targetFrame = CGRectMake(0, 0, ZFPlayer_ScreenWidth, ZFPlayer_ScreenHeight - bottomOffset);
    
    toView.alpha = 0.0f;
    bgImgView.alpha = 0;
    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        // mask 漸變效果
        bgImgView.alpha = 1;
        playerContainer.frame = targetFrame;
    } completion:^(BOOL finished) {
        toView.alpha = 1.0f;
        // 移除臨時(shí)視圖
        [bgImgView removeFromSuperview];
        [playerContainer removeFromSuperview];
        // 結(jié)束動(dòng)畫
        [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
        if (self.completion) {
            self.completion();
        }
    }];
}

- (void)startPopAnimation: (id<UIViewControllerContextTransitioning>)transitionContext
{
    // 獲取 fromView 和 toView
    UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
    UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    self.player.currentPlayerManager.view.backgroundColor = [UIColor blackColor];
    
    // 添加到動(dòng)畫容器視圖中
    UIView *container = [transitionContext containerView];
    [container addSubview:toView];
    [container addSubview:fromView];
    container.backgroundColor = [UIColor clearColor];
    
    // 添加動(dòng)畫臨時(shí)視圖到 fromView
    CGFloat bottomOffset = iPhoneX ? 83 : 0;
    CGRect normalFrame = CGRectMake(0, 0, ZFPlayer_ScreenWidth, ZFPlayer_ScreenHeight - bottomOffset);
    CGRect winFrame = CGRectZero;
    if (self.startView) {
        winFrame = [self.startView convertRect:self.startView.bounds toView:nil];
    }
    
    // 顯示圖片
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:normalFrame];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.clipsToBounds = YES;
    imageView.image = self.startImage;
    if (self.player) {
        // pop回去的時(shí)候,設(shè)置回原來的scalingMode
        self.player.currentPlayerManager.scalingMode = ZFPlayerScalingModeAspectFill;
        [self.player updateNoramlPlayerWithContainerView:imageView];
    }
    
    [container addSubview:imageView];
    
    toView.alpha = 1;
    fromView.alpha = 1;
    NSTimeInterval duration = [self transitionDuration:transitionContext];
    
    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        imageView.frame = winFrame;
        fromView.alpha = 0;
    } completion:^(BOOL finished) {
        // 移除臨時(shí)視圖
        [imageView removeFromSuperview];
        
        // 結(jié)束動(dòng)畫
        [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
        
        if (self.completion) {
            self.completion();
        }
    }];
}

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return self.duration;
}

- (UIView *)effectView {
    if (!_effectView) {
        if (@available(iOS 8.0, *)) {
            UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
            _effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
        } else {
            UIToolbar *effectView = [[UIToolbar alloc] init];
            effectView.barStyle = UIBarStyleBlackTranslucent;
            _effectView = effectView;
        }
    }
    return _effectView;
}

@end

三、相關(guān)鏈接

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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