2019-05-10直播拉流

#import "LiveViewController.h"

#import "NetworkTools.h"

#import

#import

#import "ChatRoomView.h"

#import "CommentsView.h"

#import "LiveGiftShowModel.h"

#import "LiveGiftShowCustom.h"

/// 2.颜色

#define KRGBACOLOR(r,g,b,a) [UIColor colorWithRed:(r)/255.0green:(g)/255.0blue:(b)/255.0alpha:(a)]

staticNSString*status[] = {

    @"PLPlayerStatusUnknow",

    @"PLPlayerStatusPreparing",

    @"PLPlayerStatusReady",

    @"PLPlayerStatusOpen",

    @"PLPlayerStatusCaching",

    @"PLPlayerStatusPlaying",

    @"PLPlayerStatusPaused",

    @"PLPlayerStatusStopped",

    @"PLPlayerStatusError",

    @"PLPlayerStatusCompleted"

};

@interface LiveViewController ()<PLPlayerDelegate,EMChatroomManagerDelegate,EMChatManagerDelegate,LiveGiftShowCustomDelegate>

@property (nonatomic,strong) PLPlayer *player;

@property(nonatomic,weak)UIActivityIndicatorView*activityIndicatorView;

/// 评论专区

@property (nonatomic,strong) ChatRoomView *chatRoomView;

/// 直播数据

@property (nonatomic,strong) NSMutableArray *chatDataArray;

/// 礼物区域

@property(nonatomic,weak)LiveGiftShowCustom* customGiftShow;

@property (nonatomic ,strong) NSArray <LiveGiftListModel *>* giftArr;

@property (nonatomic ,strong) NSArray * giftDataSource;

@property (nonatomic, strong) LiveUserModel *firstUser;

@property (nonatomic, strong) LiveUserModel *secondUser;

@property (nonatomic, strong) LiveUserModel *thirdUser;

@property (nonatomic, strong) LiveUserModel *fourthUser;

@property (nonatomic, strong) LiveUserModel *fifthUser;

@property (nonatomic, strong) LiveUserModel *fifthUser1;

@property (nonatomic, strong) LiveUserModel *fifthUser2;

@property (nonatomic, strong) LiveUserModel *fifthUser3;

@property (nonatomic,strong) LiveGiftListModel *giftListModel;

@end

@implementationLiveViewController

-(void)viewWillAppear:(BOOL)animated {

    [superviewWillAppear:animated];

    [self.navigationController setNavigationBarHidden:YES];

}

- (void)viewDidLoad {

    [super viewDidLoad];


    self.view.backgroundColor = [UIColor whiteColor];


    [self chatRoomUI];


    [self getPlayerUI];

}

- (void)getPlayerUI {

    NSURL*streamURL = [NSURLURLWithString:self.rtmp];

    //                weakSelf.player = [PLPlayer playerWithURL:streamURL option:weakSelf.option];

    //

    //                [weakSelf.player play];

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];


    PLPlayerOption *option = [PLPlayerOption defaultOption];

    [optionsetOptionValue:@(15) forKey:PLPlayerOptionKeyTimeoutIntervalForMediaPackets];


    self.player= [PLPlayerplayerWithURL:streamURLoption:option];


    self.player.delegate = self;


    //    [self.view addSubview:self.player.playerView];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(startPlayer) name:UIApplicationWillEnterForegroundNotification object:nil];


    [selfsetUI];

    [self startPlayer];


    [self.playerplay];

}

#pragma mark - 播放代理

/// 结束主播

- (void)player:(nonnullPLPlayer*)player stoppedWithError:(nullableNSError*)error {

    NSLog(@"%@---%@",player,error);

    // 当发生错误,停止播放时,会回调这个方法

    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        [self dismissViewControllerAnimated:YES completion:nil];

    }];

    //初始化

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"主播下播了..." message:@"" preferredStyle:UIAlertControllerStyleAlert];

    //添加操作

    [alertaddAction:alertAction];

    [self presentViewController:alert animated:YES completion:nil];

}

/// 设置播放器frame

- (void)setUI {

    if (self.player.status != PLPlayerStatusError) {

        UIView*playerView =self.player.playerView;

        playerView.backgroundColor= [UIColorwhiteColor];

        playerView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);

        //        playerView.contentMode = UIViewContentModeScaleAspectFit;

        [self.viewaddSubview:playerView];

        //        if (!playerView.superview) {

        //            playerView.contentMode = UIViewContentModeScaleAspectFit;

        //            playerView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

        //            [self.view addSubview:playerView];

        //        }



        UIButton*cancelBtn = [[UIButtonalloc]init];

        cancelBtn.frame=CGRectMake(self.view.bounds.size.width-70,20,50,50);

        [cancelBtnsetTitle:@"关闭" forState:UIControlStateNormal];

        [cancelBtnsetTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

        [playerViewaddSubview:cancelBtn];

        [cancelBtnaddTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchUpInside];


        // 评论区

        self.chatRoomView= [[ChatRoomViewalloc]init];

        self.chatRoomView.frame = CGRectMake(10, self.view.bounds.size.height-250, self.view.bounds.size.width-100, 200);

        [playerViewaddSubview:self.chatRoomView];



        CommentsView*commentsView = [[CommentsViewalloc]init];

        commentsView.frame = CGRectMake(0, self.view.bounds.size.height-50, self.view.bounds.size.width, 50);

        [playerViewaddSubview:commentsView];


        __weaktypeof(self)weakSelf =self;

        // 评论区

        [commentsViewsetCommentsBlock:^(NSString*_Nonnullcontent) {

            NSLog(@"发表评论=%@",content);


            EMTextMessageBody*body = [[EMTextMessageBodyalloc]initWithText:content];



            EMMessage*message = [[EMMessagealloc]initWithConversationID:self.chatRoomIdfrom:@"15622731953"to:self.chatRoomIdbody:bodyext:nil];


            message.chatType=EMChatTypeChatRoom;

            // 发送消息

            EMConversation*conversation = [[EMClientsharedClient].chatManagergetConversation:message.conversationIdtype:EMConversationTypeChatRoomcreateIfNotExist:YES];

            [conversationinsertMessage:messageerror:nil];


            // 更新消息

//            [[EMClient sharedClient].chatManager updateMessage:message];

//            [[EMClient sharedClient].chatManager updateMessage:message completion:^(EMMessage *aMessage, EMError *aError) {

//                NSLog(@"---%@---%@",aMessage,aError);

//

//            }];

            [[EMClientsharedClient].chatManagersendMessage:messageprogress:nilcompletion:^(EMMessage*message,EMError*error) {

                NSLog(@"---%@---%@",message,error);

                if(!error) {

//                    NSString *string = [NSString stringWithFormat:@"%@:%@",message.from,content];

                    NSAttributedString*string = [selfcontentFromColor:message.fromandText:content];

                    [self.chatDataArrayaddObject:string];


                    /// 赋值刷新

                    self.chatRoomView.dataArray = self.chatDataArray;

                }

            }];

        }];



        /// 发礼物

        [commentsViewsetGiftBlock:^(NSIndexPath*itme) {

            [weakSelfv15BtnClicked:itme];

        }];


    }

}

#pragma mark - 响应方法

- (void)cancelClick {

    [self dismissViewControllerAnimated:YES completion:nil];

}

- (void)startPlayer {

    [self addActivityIndicatorView];

    [self.playerplay];

}

/// 设置播放器view

- (void)addActivityIndicatorView {


    if (self.activityIndicatorView) {

        return;

    }

    UIActivityIndicatorView *activityIndicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];

    activityIndicatorView.center=CGPointMake(CGRectGetMidX(self.view.bounds),CGRectGetMidY(self.view.bounds));

    [self.viewaddSubview:activityIndicatorView];

    [activityIndicatorViewstopAnimating];


    self.activityIndicatorView= activityIndicatorView;

}

#pragma mark - <PLPlayerDelegate>

- (void)player:(nonnullPLPlayer*)player statusDidChange:(PLPlayerStatus)state {

    //    if (PLPlayerStatusCaching == state) {

    //        [self.activityIndicatorView startAnimating];

    //    } else {

    //        [self.activityIndicatorView stopAnimating];

    //    }

    NSLog(@"%@",status[state]);

}

#pragma mark- 聊天室

- (void)chatRoomUI {

    // 登录

//    [[EMClient sharedClient] addDelegate:self delegateQueue:nil];

//    // 注册群组回调

//    [[EMClient sharedClient].groupManager addDelegate:self delegateQueue:nil];

//    // 注册联系人回调

//    [[EMClient sharedClient].contactManager addDelegate:self delegateQueue:nil];

    // 注册信息回调

    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];;



    // 注册聊天室回调

    [[EMClient sharedClient].roomManager addDelegate:self delegateQueue:nil];


    // 加入聊天室

    [[EMClientsharedClient].roomManagerjoinChatroom:self.chatRoomIdcompletion:^(EMChatroom*aChatroom,EMError*aError) {

        NSLog(@"%@--%@",aChatroom,aError);

    }];

}

//sendMessageReadAck

/// 接收到消息列表

- (void)messagesDidReceive:(NSArray*)aMessages {

    NSLog(@"收到消息列表%@",aMessages);

    for(EMMessage*messageinaMessages) {


        EMTextMessageBody *body = (EMTextMessageBody *)message.body;


        NSAttributedString*string = [selfcontentFromColor:message.fromandText:body.text];

        [self.chatDataArrayaddObject:string];

    }


    // 赋值

    self.chatRoomView.dataArray = self.chatDataArray;

}

#pragma mark - 改变字体颜色

- (NSAttributedString*)contentFromColor:(NSString*)from andText:(NSString*)text {


    NSString*contentString = [NSStringstringWithFormat:@"%@ %@",from,text];

    NSMutableAttributedString *contentStr = [[NSMutableAttributedString alloc]initWithString:contentString];

    //找出特定字符在整个字符串中的位置

    NSRangeredRange =NSMakeRange([[contentStrstring]rangeOfString:from].location, [[contentStrstring]rangeOfString:from].length);


    //修改特定字符的颜色  235 229 177

    [contentStraddAttributes:@{NSForegroundColorAttributeName:KRGBACOLOR(235,229,177,1.0)}range:redRange];

    returncontentStr;

}

#pragma mark - 退出移除操作

- (void)dealloc {

    // 移除聊天室回调

    [[EMClient sharedClient].roomManager removeDelegate:self];

//    75415692574721

    // 退出聊天室

    [[EMClient sharedClient].roomManager leaveChatroom:self.chatRoomId completion:^(EMError *aError) {

        NSLog(@"%@",aError);

    }];

}

- (NSMutableArray*)chatDataArray {

    if (!_chatDataArray) {

        _chatDataArray= [NSMutableArrayarray];

    }

    return _chatDataArray;

}

#pragma mark - 点击屏幕

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event {

    /// 发布隐藏礼物通知

    [[NSNotificationCenter defaultCenter]postNotificationName:@"began" object:nil];

}

#pragma mark - 礼物区域

/*

 以下是测试方法:

 分别是三种添加视图的方法

 animatedWithGiftModel:  从1开始动画展示到 model.toNumber 的效果,会累加;

 addLiveGiftShowModel:  普通的从1显示礼物视图,会+=1;

 addLiveGiftShowModel: showNumber: 普通的礼物显示视图,指定显示特定数字。

 */

- (void)v15BtnClicked:(NSIndexPath*)indexPath{

    switch(indexPath.item) {

        case0:{

            LiveGiftShowModel * model = [LiveGiftShowModel giftModel:self.giftListModel userModel:self.firstUser];

//            model.toNumber = 8;

//            model.interval = 0.15;

            [self.customGiftShowanimatedWithGiftModel:model];

            break;

        }

        case1:{

            LiveGiftShowModel * model = [LiveGiftShowModel giftModel:self.giftArr[1] userModel:self.secondUser];

            [self.customGiftShowaddLiveGiftShowModel:model];

            break;

        }

        case2:{

            LiveGiftShowModel * model = [LiveGiftShowModel giftModel:self.giftArr[2] userModel:self.thirdUser];

            [self.customGiftShowanimatedWithGiftModel:model];

//            [self.customGiftShow addLiveGiftShowModel:model showNumber:99];

            break;

        }

        case3:{

            LiveGiftShowModel * model = [LiveGiftShowModel giftModel:self.giftArr[3] userModel:self.fourthUser];

//            model.toNumber = 3;

            [self.customGiftShowanimatedWithGiftModel:model];

            break;

        }

        case4:{

            LiveGiftShowModel * model = [LiveGiftShowModel giftModel:self.giftArr[4] userModel:self.fifthUser];

//            model.toNumber = 2;

            [self.customGiftShowanimatedWithGiftModel:model];

            break;

        }

        case5:{

            LiveGiftShowModel * model = [LiveGiftShowModel giftModel:self.giftArr[5] userModel:self.fifthUser1];

            [self.customGiftShowanimatedWithGiftModel:model];

            break;

        }

        case6:{

            LiveGiftShowModel * model = [LiveGiftShowModel giftModel:self.giftArr[6] userModel:self.fifthUser2];

            //            model.toNumber = 2;

            [self.customGiftShowanimatedWithGiftModel:model];

            break;

        }

        case7:{

            LiveGiftShowModel * model = [LiveGiftShowModel giftModel:self.giftArr[7] userModel:self.fifthUser3];

            [self.customGiftShowanimatedWithGiftModel:model];

            break;

        }

        default:

            break;

    }

}

/**

 弹幕移除回调代理


 @param showModel 数据模型

 */

- (void)giftDidRemove:(LiveGiftShowModel*)showModel {

    WLog(@"用户:%@ 送出了 %li 个 %@", showModel.user.name,showModel.currentNumber, showModel.giftModel.name);

}

/*

 礼物视图支持很多配置属性,开发者按需选择。

 */

- (LiveGiftShowCustom*)customGiftShow{

    if (!_customGiftShow) {

        _customGiftShow = [LiveGiftShowCustom addToView:self.view];

        _customGiftShow.addMode = LiveGiftAddModeAdd;

        [_customGiftShow setMaxGiftCount:3];

        [_customGiftShow setShowMode:LiveGiftShowModeFromTopToBottom];

        [_customGiftShow setAppearModel:LiveGiftAppearModeLeft];

        [_customGiftShow setHiddenModel:LiveGiftHiddenModeNone];

        [_customGiftShow enableInterfaceDebug:YES];

        _customGiftShow.delegate = self;

    }

    return _customGiftShow;

}

- (LiveUserModel*)firstUser {

    if (!_firstUser) {

        _firstUser= [[LiveUserModelalloc]init];

        _firstUser.name = @"么么哒";

        _firstUser.iconUrl = @"http://ww1.sinaimg.cn/large/c6a1cfeagy1ffbg8tb6wqj20gl0qogni.jpg";

    }

    return _firstUser;

}

- (LiveUserModel*)secondUser {

    if (!_secondUser) {

        _secondUser= [[LiveUserModelalloc]init];

        _secondUser.name = @"啪啪啪";

        _secondUser.iconUrl = @"http://ww1.sinaimg.cn/large/c6a1cfeagy1ffbgd5cr5nj209s0akgly.jpg";

    }

    return _secondUser;

}

- (LiveUserModel*)thirdUser {

    if (!_thirdUser) {

        _thirdUser= [[LiveUserModelalloc]init];

        _thirdUser.name = @"项圈";

        _thirdUser.iconUrl = @"http://ww1.sinaimg.cn/large/c6a1cfeagy1ffbgeuwk21j205k05kq2w.jpg";

    }

    return _thirdUser;

}

- (LiveUserModel*)fourthUser {

    if (!_fourthUser) {

        _fourthUser= [[LiveUserModelalloc]init];

        _fourthUser.name = @"比基尼";

        _fourthUser.iconUrl = @"http://ww1.sinaimg.cn/large/c6a1cfeagy1ffbgfpf5bgj205k07v3yk.jpg";

    }

    return _fourthUser;

}

- (LiveUserModel*)fifthUser {

    if (!_fifthUser) {

        _fifthUser= [[LiveUserModelalloc]init];

        _fifthUser.name = @"上上签";

        _fifthUser.iconUrl = @"http://ww1.sinaimg.cn/large/c6a1cfeagy1ffbgg5427qj205k05k748.jpg";

    }

    return _fifthUser;

}

- (LiveUserModel*)fifthUser1 {

    if (!_fifthUser1) {

        _fifthUser1= [[LiveUserModelalloc]init];

        _fifthUser1.name = @"法拉利";

        _fifthUser1.iconUrl = @"http://ww1.sinaimg.cn/large/c6a1cfeagy1ffbgg5427qj205k05k748.jpg";

    }

    return _fifthUser1;

}

- (LiveUserModel*)fifthUser2 {

    if (!_fifthUser2) {

        _fifthUser2= [[LiveUserModelalloc]init];

        _fifthUser2.name = @"壁咚";

        _fifthUser2.iconUrl = @"http://ww1.sinaimg.cn/large/c6a1cfeagy1ffbgg5427qj205k05k748.jpg";

    }

    return _fifthUser2;

}

- (LiveUserModel*)fifthUser3 {

    if (!_fifthUser3) {

        _fifthUser3= [[LiveUserModelalloc]init];

        _fifthUser3.name = @"浪漫热气球";

        _fifthUser3.iconUrl = @"http://ww1.sinaimg.cn/large/c6a1cfeagy1ffbgg5427qj205k05k748.jpg";


    }

    return _fifthUser3;

}

- (LiveGiftListModel*)giftListModel {

    if (!_giftListModel) {

        _giftListModel = [[LiveGiftListModel alloc]init];

        _giftListModel.picUrl = @"http://ww1.sinaimg.cn/large/c6a1cfeagy1ffbgg5427qj205k05k748.jpg";

    }

    return _giftListModel;

}

@end

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

推荐阅读更多精彩内容