前言
項目中要在原有的視頻基礎上添加彈幕功能,主要包含開始、停止、暫停、恢復、發送彈幕、彈幕點擊等小功能。找到之前一個封裝的彈幕庫,在原有的基礎上做了些功能改動和添加,寫在這裏記錄一下。
項目層級關係
DanmuSend
這塊兒主要是負責發送彈幕功能
包含DanmuSendView
和DanmuOperateView
,LGJDanmuOperateView
主要承載彈出輸入框功能,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
遍歷danmuInfos
從danmuInfos
(彈幕信息)中獲取彈幕文字內容、創建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];
}
}];
}
});
}
主要的功能點就是這些,但是具體的細節還是在代碼裏面,但是實現方式也不侷限與代碼中的這一種,每個人有每個人的思路,要是覺得有些地方比較晦澀也可以使用別的方式代替。這個基本上可以滿足平常視頻彈幕的基本功能需求了。
代碼鏈接: