iOS视频弹幕

前言

项目中要在原有的视频基础上添加弹幕功能,主要包含开始、停止、暂停、恢复、发送弹幕、弹幕点击等小功能。找到之前一个封装的弹幕库,在原有的基础上做了些功能改动和添加,写在这里记录一下。

项目层级关系

屏幕快照 2019-11-25 下午4.09.19.png

DanmuSend

这块儿主要是负责发送弹幕功能
包含DanmuSendViewDanmuOperateViewLGJDanmuOperateView主要承载弹出输入框功能,DanmuSendView主要是监听键盘及输入内容。

Danmu

这块儿是主要的弹幕逻辑区域
LGJDanmuUtil 配置弹幕字体大小、颜色等个性化定制
LGJDanmuLabel 弹幕显示label
LGJDanmuView 弹幕显示view,主要承载弹幕的label和头像img
LGJDanmuBgView 弹幕显示的背景view
LGJDanmuManager 弹幕功能的管理类

使用

在需要用到弹幕的vc中引入头文件:
#import "LGJDanmuManager.h"
#import "LGJDanmuSendView.h"

这里呢,使用了本地文件临时充当服务器返回的对应时间点的弹幕文字。

NSString *path = [[NSBundle mainBundle] bundlePath];
    path = [[path stringByAppendingPathComponent:@"LGJDanmuSource"] stringByAppendingPathExtension:@"plist"];
    NSArray *tempInfos = [NSArray arrayWithContentsOfFile:path];
    
    NSArray *infos = [tempInfos sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        CGFloat v1 = [[obj1 objectForKey:kDanmuTimeKey] floatValue];
        CGFloat v2 = [[obj2 objectForKey:kDanmuTimeKey] floatValue];
        
        NSComparisonResult result = v1 <= v2 ? NSOrderedAscending : NSOrderedDescending;
        
        return result;
    }];

初始化弹幕管理类:

self.danmuManager = [[LGJDanmuManager alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, _screenV.bounds.size.height) data:infos inView:_screenV durationTime:1];
    
    self.countTime = -1;
    [self.danmuManager initStart];

_screenV模拟的视频播放view。

弹幕点击事件方法:

- (void)addTapGesture {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHandler:)];
    tap.cancelsTouchesInView = NO;
    [self.screenV addGestureRecognizer:tap];
}

- (void)tapHandler:(UITapGestureRecognizer *)gesture {
    [self.danmuManager.danmuBgView dealTapGesture:gesture block:^(LGJDanmuView *danmuView){
        NSLog(@"点击了:-- %@", danmuView.danmuLabel.text);
    }];
}

在这个vc中还需要有横竖屏切换的监听方法以及对应的处理方法:

- (void)p_prepare {
    [self.danmuSendV backAction];
    [self p_destoryTimer];
    BOOL bPlaying = self.bPlaying;
    [self stop:nil];
    self.bPlaying = bPlaying;
    [self.danmuManager resetDanmuWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, _screenV.bounds.size.height)];
}

发送弹幕的代理方法:

#pragma mark - LGJDanmuSendViewDelegate

- (void)sendDanmu:(LGJDanmuSendView *)danmuSendV info:(NSString *)info {
    NSDate *now = [NSDate new];
    double t = ((double)now.timeIntervalSince1970);
    t = ((int)t)%1000;
    CGFloat nowTime = self.countTime + t*0.0001;
    [self.danmuManager insertDanmu:@{kDanmuContentKey:info, kDanmuTimeKey:@(nowTime), kDanmuOptionalKey:@"df"}];
    
    if (self.bPlaying)
        [self resume:nil];
}

- (void)closeSendDanmu:(LGJDanmuSendView *)danmuSendV {
    if (self.bPlaying)
        [self resume:nil];
}

点击开始按钮,开始滚动弹幕

- (IBAction)start:(id)sender {
    [self.danmuManager initStart];
    self.bPlaying = YES;
    
    if ([_timer isValid]) {
        return;
    }
    if (_timer == nil) {
        __weak typeof(self) weakSelf = self;
        self.timer = [NSTimer eoc_scheduledTimerWithTimeInterval:1 block:^{
            ViewController *strogSelf = weakSelf;
            [strogSelf progressVideo];
        } repeats:YES];
    }
}

- (void)progressVideo {
    self.countTime++;
    [_danmuManager rollDanmu:_countTime];
}

LGJDanmuManager

这个类是弹幕的管理类,主要的方法及实现方法都在这里

首先初始化数据
- (instancetype)initWithFrame:(CGRect)frame data:(NSArray *)infos inView:(UIView *)view durationTime:(NSUInteger)time {
    self = [super init];
    if (self) {
//        self.frame = frame;
        CGRect tempFrame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, 100);
        self.frame = tempFrame;
        self.infos = [infos mutableCopy];
        self.superView = view;
        self.durationTime = time;
        
        self.danmuQueue = dispatch_queue_create("com.danmu.queue", NULL);
        
        [self p_initInfo];
    }
    return self;
}

#pragma mark - Private

- (void)p_initInfo {
    _countChannel = self.frame.size.height/CHANNEL_HEIGHT;
    
    self.arRollChannelInfo = [NSMutableArray arrayWithCapacity:_countChannel];
    self.arFadeChannelInfo = [NSMutableArray arrayWithCapacity:2];
    
    NSUInteger sectionLines = nearbyintf((CGFloat)_countChannel / 3);
    NSUInteger firstLines = MAX(_countChannel - sectionLines*2, sectionLines);
    //滚动航道布局
    {
        //上中下,假设10,上:0-3,中:4-6,下:7-9
        _upPosition = (DanmuPositionStruct){0, firstLines};
        _middlePosition = (DanmuPositionStruct){_upPosition.length, sectionLines};
        _downPosition = (DanmuPositionStruct){_middlePosition.start + _middlePosition.length, _countChannel - _middlePosition.start - _middlePosition.length};
        //上中下,假设10,上:0-9,中:4-9,下:7-9
        _upPosition = (DanmuPositionStruct){0, _countChannel};
        _middlePosition = (DanmuPositionStruct){firstLines, _upPosition.length - firstLines};
        _downPosition = (DanmuPositionStruct){_middlePosition.start + sectionLines, _upPosition.length - firstLines - sectionLines};
    }
    //浮现航道布局,这里选择的是上面滚动航道布局,所以不一定是现在这样子
    {
        //第一层:上中下,假设10,上:0-9,中:4-9,下:7-9,
        _upFadeOnePosition = _upPosition;
        _middleFadeOnePosition = _middlePosition;
        _downFadeOnePosition = _downPosition;
        //由于上一层为10,第二层为9,上:0-8,中:4-8,下:7-8
        _upFadeTwoPosition = (DanmuPositionStruct){_upFadeOnePosition.start, _upFadeOnePosition.length - 1};
        _middleFadeTwoPosition = (DanmuPositionStruct){_middleFadeOnePosition.start, _middleFadeOnePosition.length - 1};
        _downFadeTwoPosition = (DanmuPositionStruct){_downFadeOnePosition.start, _downFadeOnePosition.length - 1};
    }
    
    _danmuManagerState = DanmuManagerStateWait;
}

- (void)p_initData {
    [self.arRollChannelInfo removeAllObjects];
    
    for (int i = 0; i < _countChannel; i++) {
        [self.arRollChannelInfo addObject:[NSNumber numberWithInt:i]];
    }
    
    [self.arFadeChannelInfo removeAllObjects];
    
    NSMutableArray *ar1 = [NSMutableArray new];
    for (int i = 0; i < _countChannel; i++) {
        [ar1 addObject:[NSNumber numberWithInt:i]];
    }
    [self.arFadeChannelInfo addObject:ar1];
    NSMutableArray *ar2 = [NSMutableArray new];
    for (int i = 0; i < _countChannel - 1; i++) {
        [ar2 addObject:[NSNumber numberWithInt:i]];
    }
    [self.arFadeChannelInfo addObject:ar2];
    
    self.currentIndex = 0;
    
    [self.danmuBgView removeFromSuperview];
    self.danmuBgView = nil;
    LGJDanmuBgView *danmuBgView = [[LGJDanmuBgView alloc] initWithFrame:_frame];
    self.danmuBgView = danmuBgView;
    self.danmuBgView.backgroundColor = [UIColor lightGrayColor];
    [self.superView addSubview:self.danmuBgView];
    
    _danmuManagerState = DanmuManagerStateWait;
}
开始滚动弹幕

- (void)p_danmu:(NSTimeInterval)startTime
遍历danmuInfosdanmuInfos(弹幕信息)中获取弹幕文字内容、创建danmuView,对新创建的danmuView选择出合适的航道,获取到合适的航道后开始动画。主要原理是这样,至于合适的航道怎么选择,可以参考代码。

//选择在不超出缓冲区的且缓冲区最长的航道
- (NSUInteger)p_allChannelWithPosition:(DanmuPositionStruct)danmuPosition new:(LGJDanmuView *)newDanmuL {
    CGFloat width = CHANNEL_WIDTH_MAX;
    NSUInteger index = NSNotFound;
    for (int i = (int)danmuPosition.start; i < danmuPosition.start + danmuPosition.length; i++) {id obj = [self.arRollChannelInfo objectAtIndex:i];
        if ([obj isKindOfClass:[LGJDanmuView class]]) {
            CGFloat rightX = ((LGJDanmuView *)obj).currentRightX;
            if (rightX <= CHANNEL_WIDTH_MAX) {
                CGFloat xx = rightX;
                if (xx < width) {
                    width = xx;
                    index = i;
                }
            }
        }
    }
    
    return index;
}
//选择不会碰撞的航道
- (BOOL)p_last:(LGJDanmuView *)lastDanmuL new:(LGJDanmuView *)newDanmuL {
    CGFloat durationTime = newDanmuL.startTime - lastDanmuL.startTime;
    if (durationTime > newDanmuL.animationDuartion) {
        return YES;
    }
    CGFloat timeS = lastDanmuL.frame.size.width/lastDanmuL.speed;
    if (timeS >= durationTime) {
        return NO;
    }
    CGFloat timeE = newDanmuL.currentRightX/newDanmuL.speed;
    if (timeE <= durationTime) {
        return NO;
    }
    
    return YES;
}
#获取合适的航道、danmuView、offsetXY
- (void)p_getRollBestChannel:(LGJDanmuView *)newDanmuL completion:(void(^)(NSUInteger idx, CGFloat offsetX))completion {
    DanmuPositionStruct danmuPosition;
    if (newDanmuL.isPositionMiddle) {
        danmuPosition = _middlePosition;
    }
    else if (newDanmuL.isPositionBottom) {
        danmuPosition = _downPosition;
    }
    else {
        danmuPosition = _upPosition;
    }
    
    NSUInteger index = danmuPosition.start;
    BOOL bFind = NO;
    for (int i = (int)danmuPosition.start; i < danmuPosition.start + danmuPosition.length; i++) {
        id obj = [self.arRollChannelInfo objectAtIndex:i];
        index = i;
        if ([obj isKindOfClass:[LGJDanmuView class]]) {
            bFind = [self p_last:obj new:newDanmuL];
        }else {
            bFind = YES;
        }
        
        if (bFind)
            break;
    }
    
    if (bFind) {
        id obj = [self.arRollChannelInfo objectAtIndex:index];
        [self.arRollChannelInfo replaceObjectAtIndex:index withObject:newDanmuL];
        if ([obj isKindOfClass:[LGJDanmuView class]]) {
            CGFloat x = ((LGJDanmuView *)obj).currentRightX;
            completion(index, x < 0 ? 0 : x);
        }else
            completion(index, 0);
    }else {
        if (index < danmuPosition.start + danmuPosition.length - 1) {
            index += 1;
            [self.arRollChannelInfo replaceObjectAtIndex:index withObject:newDanmuL];
            completion(index, 0);
        }
        else {
            NSUInteger index = NSNotFound;
            index = [self p_allChannelWithPosition:danmuPosition new:newDanmuL];
            if (index != NSNotFound) {
                LGJDanmuView *obj = [self.arRollChannelInfo objectAtIndex:index];
                [self.arRollChannelInfo replaceObjectAtIndex:index withObject:newDanmuL];
                CGFloat x = obj.currentRightX;
                completion(index, x < CHANNEL_SPACE ? CHANNEL_SPACE : x);
            }else
                completion(NSNotFound, 0);
        }
    }
}
停止
- (void)stop {
    dispatch_sync(self.danmuQueue, ^{
        _danmuManagerState = DanmuManagerStateStop;
        [self.arRollChannelInfo removeAllObjects];
        [self.arFadeChannelInfo removeAllObjects];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.danmuBgView.subviews makeObjectsPerformSelector:@selector(removeDanmu)];
            [self.danmuBgView removeFromSuperview];
        });
    });
}
暂停
- (void)pause {
    if (_danmuManagerState != DanmuManagerStateAnimationing)
        return;
    dispatch_sync(self.danmuQueue, ^{
        _danmuManagerState = DanmuManagerStatePause;
        [self.danmuBgView.subviews makeObjectsPerformSelector:@selector(pause)];
    });
}
恢复
- (void)resume:(NSTimeInterval)nowTime {
    if (_danmuManagerState != DanmuManagerStatePause)
        return;
    dispatch_sync(self.danmuQueue, ^{
        _danmuManagerState = DanmuManagerStateAnimationing;
        for (id subview in self.danmuBgView.subviews) {
            if ([subview isKindOfClass:[LGJDanmuView class]]) {
                [(LGJDanmuView *)subview resume:nowTime];
            }
        }
    });
}
插入新弹幕
- (void)insertDanmu:(NSDictionary *)info {
    dispatch_sync(self.danmuQueue, ^{
        id optional = [LGJDanmuUtil defaultOptions];
        __block LGJDanmuView *danmuView = [LGJDanmuView createWithInfo:info optional:optional inView:self.danmuBgView hasHeaderIcon:YES];
        if ([danmuView isMoveModeFadeOut]) {
            [self p_getFadeBestChannel:danmuView completion:^(NSUInteger idx, CGFloat offsetY) {
                if (idx != NSNotFound) {
                    [danmuView setDanmuChannel:idx offset:offsetY];
                }
            }];
        }
        else {
            [self p_getRollBestChannel:danmuView completion:^(NSUInteger idx, CGFloat offsetX) {
                if (idx != NSNotFound) {
                    [danmuView setDanmuChannel:idx offset:offsetX];
                }
            }];
        }
    });
}

主要的功能点就是这些,但是具体的细节还是在代码里面,但是实现方式也不局限与代码中的这一种,每个人有每个人的思路,要是觉得有些地方比较晦涩也可以使用别的方式代替。这个基本上可以满足平常视频弹幕的基本功能需求了。

代码链接:

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,636评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,890评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,680评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,766评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,665评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,045评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,515评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,182评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,334评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,274评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,319评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,002评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,599评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,675评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,917评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,309评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,885评论 2 341

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,076评论 1 32
  • 记忆像扇窗, 蛛丝儿锁回想。 一纸浮华流淌, 激起多少飞浪。 时光已窖藏, 揽一袖花香, 再忆当年小白杨, 花絮飞...
    达令简阅读 383评论 1 7
  • 哪一刻你会深感生活不易? 这些天上海一直在下雨,可能很多人觉得一直下雨也没什么影响,可是对于像我这样每天上下班还有...
    十月听风阅读 402评论 4 5
  • 想了想,朋友说的很有道理。我就问他对于这方面你有什么好的建议。 朋友接着说,建议算不上。不过你要形成一个强制自己储...
    一甲之言阅读 207评论 0 0
  • 今天没有任务,正好理清一下自己的思路! 还缺少21个模特,未来的21天会更加辛苦,也会更有收获,每天在工作之余都会...
    张小龙灬阅读 212评论 0 0