实现直播软件源码中语音直播间最小化功能
云豹直播软件源码中,语音直播间(又称语音聊天室)可以实现“退出直播间后最小化浮窗显示”功能,当未上麦的普通用户在离开语音直播间时,可以把直播间最小化而非关闭,即可在首页展示悬浮窗,并继续旁听直播间中的语音信息,该功能可以使用通知的方式进行实现。
首先,在直播软件源码中,需要展示悬浮窗的界面里添加通知、创建悬浮窗展示视图、创建语音播放器,直播软件源码示例如下:
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(showChatLiveView:) name:@"SHOWCHATLIVE" object:nil];
[[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"isShowChatLive"];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hideChatRoomLiewView) name:@"HIDELIVEVIEW" object:nil];
chatView = [[UIView alloc]init];
chatView.frame = CGRectMake(_window_width-103, _window_height *0.7, 103, 32);
chatView.backgroundColor = RGB(236, 87, 101);
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:chatView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft cornerRadii:CGSizeMake(16, 16)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = chatView.bounds;
maskLayer.path = maskPath.CGPath;
chatView.layer.mask = maskLayer;
// [self.view addSubview:chatView];
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = chatView.bounds;
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(1, 0);
gradientLayer.locations = @[@(0),@(1.0)];//渐变点
[gradientLayer setColors:@[(id)[RGB(236,87,101) CGColor],(id)[RGB(252,176,141) CGColor]]];//渐变数组
[chatView.layer addSublayer:gradientLayer];
[[UIApplication sharedApplication].keyWindow addSubview:chatView];
headImg = [[UIImageView alloc]init];
headImg.frame = CGRectMake(2, 2, 28, 28);
headImg.layer.cornerRadius = 14;
headImg.layer.masksToBounds = YES;
headImg.backgroundColor = RGB(250, 250, 250);
[chatView addSubview:headImg];
nameLb = [[UILabel alloc]init];
nameLb.frame = CGRectMake(headImg.right+5, 2, chatView.width-40, 15);
nameLb.font = [UIFont systemFontOfSize:10];
nameLb.textColor = [UIColor whiteColor];
nameLb.text = @"ssakjkjka";
[chatView addSubview:nameLb];
idLb = [[UILabel alloc]init];
idLb.frame = CGRectMake(headImg.right+5, nameLb.bottom, chatView.width-40, 15);
idLb.font = [UIFont systemFontOfSize:10];
idLb.textColor = [UIColor whiteColor];
idLb.text = @"ID:1112212";
[chatView addSubview:idLb];
chatView.hidden = YES;
UIButton *roomBtn = [UIButton buttonWithType:0];
roomBtn.frame = CGRectMake(0, 0, chatView.width, chatView.height);
[roomBtn addTarget:self action:@selector(roomBtnClick) forControlEvents:UIControlEventTouchUpInside];
[chatView addSubview:roomBtn];
_config = [[TXLivePlayConfig alloc] init];
_config.headers = @{@"referer":h5url};
//_config.enableAEC = YES;
//自动模式
_config.bAutoAdjustCacheTime = YES;
_config.minAutoAdjustCacheTime = 1;
_config.maxAutoAdjustCacheTime = 5;
_config.connectRetryCount = 1;
_config.connectRetryInterval = 3;
_txLivePlayer =[[TXLivePlayer alloc] init];
if (ios8) {
_txLivePlayer.enableHWAcceleration = false;
}else{
_txLivePlayer.enableHWAcceleration = YES;
}
[_txLivePlayer setConfig:_config];当未上麦的普通用户点击关闭直播间按钮时,弹出选择聊天室最小化功能,用户点击最小化时,发送通知展示悬浮窗,同时把直播间信息返回,具体直播软件源码如下:
//页面退出
-(void)returnCancless{
smallShowAlert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *defaultActionss = [UIAlertAction actionWithTitle:YZMsg(@"退出直播间") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self dissmissVC];
[self signOutWatchLive];
}];
UIAlertAction *smallAction;
if (!isHaveUpMic) {
smallAction = [UIAlertAction actionWithTitle:YZMsg(@"聊天室最小化") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[[NSNotificationCenter defaultCenter]postNotificationName:@"SHOWCHATLIVE" object:nil userInfo:self.playDoc];
[self dissmissVC];
}];
}
UIAlertAction*cancelAction = [UIAlertAction actionWithTitle:YZMsg(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}];
[defaultActionss setValue:RGBA(252,43,43,1) forKey:@"_titleTextColor"];
[smallAction setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
[cancelAction setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
[smallShowAlert addAction:smallAction];
[smallShowAlert addAction:defaultActionss];
[smallShowAlert addAction:cancelAction];
[self presentViewController:smallShowAlert animated:YES completion:nil];
}当首页收到通知,解析数据展示,并播放语音直播间的流,直播软件源码示例如下:
-(void)showChatLiveView:(NSNotification *)noti{
chatView.frame = CGRectMake(_window_width-103, _window_height *0.7, 103, 32);
currentChatDic = noti.userInfo;
chatView.hidden = NO;
NSLog(@"传回来的数据----:%@",noti.userInfo);
[headImg sd_setImageWithURL:[NSURL URLWithString:minstr([currentChatDic valueForKey:@"thumb"])]];
nameLb.text = minstr([currentChatDic valueForKey:@"user_nicename"]);
idLb.text =[NSString stringWithFormat:@"ID:%@",minstr([currentChatDic valueForKey:@"uid"])];
[[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"isShowChatLive"];
[[NSUserDefaults standardUserDefaults]setObject:currentChatDic forKey:@"SMALLCHATDATA"];
if(_txLivePlayer != nil)
{
_txLivePlayer.delegate = self;
NSString *playUrl = minstr([currentChatDic valueForKey:@"pull"]);
NSInteger _playType = 0;
if ([playUrl hasPrefix:@"rtmp:"]) {
_playType = PLAY_TYPE_LIVE_RTMP;
} else if (([playUrl hasPrefix:@"https:"] || [playUrl hasPrefix:@"http:"]) && [playUrl rangeOfString:@".flv"].length > 0) {
_playType = PLAY_TYPE_LIVE_FLV;
}
else{
}
if ([playUrl rangeOfString:@".mp4"].length > 0) {
_playType = PLAY_TYPE_VOD_MP4;
}
if ([playUrl rangeOfString:@".m3u8"].length > 0) {
_playType = PLAY_TYPE_VOD_FLV;
}
int result = [_txLivePlayer startPlay:playUrl type:_playType];
NSLog(@"wangminxin%d",result);
if (result == -1)
{
}
if( result != 0)
{
[_notification displayNotificationWithMessage:@"视频流播放失败" forDuration:5];
}
if( result == 0){
NSLog(@"播放视频");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
});
}
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
}
}
//播放监听事件
-(void) onPlayEvent:(int)EvtID withParam:(NSDictionary*)param
{
dispatch_async(dispatch_get_main_queue(), ^{
if (EvtID == PLAY_EVT_CONNECT_SUCC) {
NSLog(@"play_linkMic已经连接服务器");
}
else if (EvtID == PLAY_EVT_RTMP_STREAM_BEGIN){
NSLog(@"play_linkMic已经连接服务器,开始拉流");
}
else if (EvtID == PLAY_EVT_PLAY_BEGIN){
NSLog(@"play_linkMic视频播放开始");
}
else if (EvtID== PLAY_WARNING_VIDEO_PLAY_LAG){
NSLog(@"play_linkMic当前视频播放出现卡顿(用户直观感受)");
}
else if (EvtID == PLAY_EVT_PLAY_END){
NSLog(@"play_linkMic视频播放结束");
[self hideChatRoomLiewView];
}
else if (EvtID == PLAY_ERR_NET_DISCONNECT) {
NSLog(@"play_linkMic网络断连,且经多次重连抢救无效,可以放弃治疗,更多重试请自行重启播放");
[self hideChatRoomLiewView];
}
});
}语音悬浮窗添加手动拖动功能,在悬浮窗view上添加手势功能,获取在横坐标、纵坐标拖动了多少像素,并且减去顶部和底部tabbar的距离
- (void)dragViewMoved:(UIPanGestureRecognizer *)panGestureRecognizer
{
if (panGestureRecognizer.state == UIGestureRecognizerStateChanged) {
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
//返回在横坐标上、纵坐标上拖动了多少像素
CGPoint point = [panGestureRecognizer translationInView:self.view];
NSLog(@"%f,%f",point.x,point.y);
CGFloat centerX = panGestureRecognizer.view.center.x+point.x;
CGFloat centerY = panGestureRecognizer.view.center.y+point.y;
CGSize viewSize = panGestureRecognizer.view.frame.size;
// top
if (centerY - viewSize.height/2 < 0) {
centerY = viewSize.height/2+statusbarHeight+ShowDiff+55;
}
// bottom
if (centerY + viewSize.height/2 > screenHeight) {
centerY = screenHeight - viewSize.height/2-55;
}
// left
if (centerX - viewSize.width/2 < 0){
centerX = viewSize.width/2;
}
// right
if (centerX + viewSize.width/2 > screenWidth){
centerX = screenWidth - viewSize.width/2;
}
panGestureRecognizer.view.center = CGPointMake(centerX, centerY);
//拖动完之后,每次都要用setTranslation:方法置0这样才不至于不受控制般滑动出视图
[panGestureRecognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}
}当点击悬浮窗时,停止播流并且验证语音直播间信息,进入语音直播间,同时隐藏悬浮窗,直播软件源码如下:
- (void)stopConnect{
[[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"isShowChatLive"];
if(_txLivePlayer != nil)
{
_txLivePlayer.delegate = nil;
[_txLivePlayer stopPlay];
}
}
-(void)checklive:(NSString *)stream andliveuid:(NSString *)liveuid{
NSString *url = [purl stringByAppendingFormat:@"?service=Live.checkLive"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
request.timeoutInterval = 5.0;
request.HTTPMethod = @"post";
NSString *param = [NSString stringWithFormat:@"uid=%@&token=%@&liveuid=%@&stream=%@",[Config getOwnID],[Config getOwnToken],liveuid,stream];
request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
NSURLResponse *response;
NSError *error;
NSData *backData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error) {
[MBProgressHUD showError:@"无网络"];
}
else{
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:backData options:NSJSONReadingMutableContainers error:nil];
NSNumber *number = [dic valueForKey:@"ret"];
if([number isEqualToNumber:[NSNumber numberWithInt:200]])
{
NSArray *data = [dic valueForKey:@"data"];
NSString *code = [NSString stringWithFormat:@"%@",[data valueForKey:@"code"]];
if([code isEqual:@"0"])
{
NSDictionary *info = [[data valueForKey:@"info"] firstObject];
NSString *type = [NSString stringWithFormat:@"%@",[info valueForKey:@"type"]];
type_val = [NSString stringWithFormat:@"%@",[info valueForKey:@"type_val"]];
livetype = [NSString stringWithFormat:@"%@",[info valueForKey:@"type"]];
_sdkType = minstr([info valueForKey:@"live_sdk"]);
NSString *live_type =minstr([info valueForKey:@"live_type"]);
if ([live_type isEqual:@"1"]) {
UserRoomViewController *chatroom = [[UserRoomViewController alloc]init];
chatroom.playDoc = currentChatDic;
[[MXBADelegate sharedAppDelegate] pushViewController:chatroom animated:YES];至此,直播软件源码中,关于语音直播间悬浮窗功能的基本完成,完美实现“直播间最小化”等一系列要求,日后更多关于直播软件开发的文章会逐渐放出,请关注云豹科技,如果有购买直播软件源码需求,也请联系我们的客服。
声明:以上内容为作者本人原创,未经作者本人同意,禁止转载,否则将追究相关法律责任www.yunbaokj.com






鲁公网安备 37090202000844号

