TXLiveRoomViewController.m 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832
  1. //
  2. // TXLiveRoomViewController.m
  3. // StudentDaya
  4. //
  5. // Created by 王智 on 2023/2/21.
  6. // Copyright © 2023 DayaMusic. All rights reserved.
  7. //
  8. #import "TXLiveRoomViewController.h"
  9. #import "TXLiteAVSDK_Professional/TXLiteAVSDK.h"
  10. #import "KSLiveEmptyView.h"
  11. #import "TXLiveVideoView.h"
  12. #import "LiveRoomHeadView.h"
  13. #import "LiveRoomBottomView.h"
  14. #import <Lottie/Lottie.h>
  15. #import "KSChatInputBarControl.h"
  16. #import "TXLiveChatListCell.h"
  17. #import "AppDelegate.h"
  18. #import "UIDevice+TFDevice.h"
  19. #import "LiveRoomLikeLayer.h"
  20. #import "LiveAlertView.h"
  21. #import "KSShopCardView.h"
  22. #import "KSLiveWebViewController.h"
  23. #import "KSLiveBadNetView.h"
  24. #import "KSLiveEndView.h"
  25. #import "LiveAnimationView.h"
  26. #import "LiveApplyView.h"
  27. #import "LiveApplyingView.h"
  28. #import <ImSDK_Plus/ImSDK_Plus.h>
  29. #import "TXIMLinsenter.h"
  30. #import "TXLiveMessageModel.h"
  31. #import "TXLiveURLUtils.h"
  32. #import "TXLiveMessageCenter.h"
  33. #import "KSDragWindowManager.h"
  34. #import "TXLiveLoadingView.h"
  35. #import "TXUISeatMember.h"
  36. #import "TXSeatContainerView.h"
  37. #import "LiveRoomConfirmAlert.h"
  38. #import "LiveModuleService.h"
  39. #define AUTOHIDE_TIME (10.0f)
  40. typedef NS_ENUM(NSInteger, MICSTATUS) {
  41. MICSTATUS_NOMAL, // 正常状态
  42. MICSTATUS_WAITING, // 申请中
  43. MICSTATUS_CONNECTING, // 连麦中
  44. };
  45. @interface TXLiveRoomViewController ()<UIGestureRecognizerDelegate,KSChatInputBarControlDelegate,UITableViewDataSource,UITableViewDelegate,V2TXLivePlayerObserver,TRTCCloudDelegate>
  46. // 是否是观众
  47. @property (nonatomic, assign) BOOL isAudience;
  48. // rtc 连麦时使用
  49. @property (nonatomic, strong) TRTCCloud *trtcCloud;
  50. @property (nonatomic, strong) V2TXLivePlayer *livePlayer;
  51. @property (nonatomic, strong) LiveRoomHeadView *headView;
  52. @property (nonatomic, copy) LiveRoomBottomView *bottomView;
  53. // 视频主窗口容器
  54. @property (nonatomic, strong) UIView *videoContainerView;
  55. // 主屏videoView
  56. @property (nonatomic, strong) UIView *videoView;
  57. // 画面渲染的画面
  58. @property (nonatomic, strong) TXLiveVideoView *videoRenderView;
  59. // 切换按钮
  60. @property (nonatomic, strong) UIButton *switchButton;
  61. @property (nonatomic, strong) LOTAnimationView *animationView;
  62. /// 连麦的视图
  63. @property (nonatomic, strong) TXSeatContainerView *seatContainer;
  64. // 聊天UI
  65. /*!
  66. 消息列表CollectionView和输入框都在这个view里
  67. */
  68. @property(nonatomic, strong) UIView *messageContentView;
  69. /*!
  70. 会话页面的TableView
  71. */
  72. @property (nonatomic, strong) UITableView *conversationMessageTableView;
  73. /*!
  74. 聊天内容的消息Cell数据模型的数据源
  75. @discussion 数据源中存放的元素为消息Cell的数据模型,即RCDLiveMessageModel对象。
  76. */
  77. @property(nonatomic, strong) NSMutableArray<TXLiveMessageModel *> *conversationDataRepository;
  78. /**
  79. 输入工具栏
  80. */
  81. @property(nonatomic,strong) KSChatInputBarControl *inputBar;
  82. /**
  83. * 是否需要滚动到底部
  84. */
  85. @property(nonatomic, assign) BOOL isNeedScrollToButtom;
  86. /**
  87. 上次点赞按钮点击时间
  88. */
  89. @property(nonatomic, assign) NSTimeInterval lastClickPraiseTime;
  90. @property (nonatomic, assign) BOOL landScape;
  91. @property (nonatomic, assign) BOOL isHiddenHeadView;
  92. // 连麦状态
  93. @property (nonatomic, assign) MICSTATUS micStatus;
  94. @property (nonatomic, strong) LiveApplyView *applyView; // 未申请
  95. @property (nonatomic, strong) LiveApplyingView *applyingView; // 申请中
  96. @property (nonatomic, assign) BOOL isCreaterVideoEnable;
  97. @property (nonatomic, assign) BOOL isCloseRoom; // 是否直播结束
  98. /// 提示窗
  99. @property (nonatomic, strong) LiveAlertView *alertView;
  100. @property (nonatomic, strong) KSShopCardView *cardView;
  101. @property (nonatomic, assign) NSTimeInterval lastSendMsgTime;
  102. @property (nonatomic, strong) LiveAnimationView *enterAnimationView;
  103. @property (nonatomic, strong) KSLiveEndView *endView; // 直播结束显示的画面
  104. @property (nonatomic, strong) KSLiveEmptyView *emptyView;
  105. @property (nonatomic, strong) KSLiveBadNetView *netBadView;
  106. /// 是否在切换身份
  107. @property (nonatomic, assign) BOOL isTransferRole;
  108. @property (nonatomic, assign) BOOL hasSendWelcomeMessage;
  109. // 远端连麦用户
  110. @property (nonatomic, strong) NSMutableArray *remoteMemberArray;
  111. @property (nonatomic, assign) BOOL isPauseLive;
  112. @property (nonatomic, strong) TXLiveLoadingView *loadingView;
  113. @property (nonatomic, assign) BOOL hasShowSuspendView;
  114. @property (nonatomic, assign) BOOL muteRoomMic;
  115. @property (nonatomic, assign) BOOL micEnable;
  116. @property (nonatomic, strong) LiveRoomConfirmAlert *closeAlert;
  117. @property (nonatomic, assign) BOOL isConnectedFailed;
  118. #pragma mark --- 时间统计
  119. // 后端返回进入教室时间戳 ms
  120. @property (nonatomic, assign) NSTimeInterval enterTime;
  121. // 进入教室时间date
  122. @property (nonatomic, strong) NSDate *enterDate;
  123. @end
  124. // 用于记录点赞消息连续点击的次数
  125. static int clickPraiseBtnTimes = 0;
  126. @implementation TXLiveRoomViewController
  127. - (instancetype)init {
  128. self = [super init];
  129. if (self) {
  130. [self defaultConfig];
  131. [self default3AConfig];
  132. }
  133. return self;
  134. }
  135. - (void)default3AConfig {
  136. self.ANS = 0;
  137. self.AEC = 100;
  138. self.AGC = 0;
  139. }
  140. - (void)joinChatRoom {
  141. if (TXIM_LINSENTER.loginIMSuccess == NO) {
  142. [TXIM_LINSENTER TXIMLoginWithUserId:UserDefault(IM_USERID) sig:self.UserSig callback:^(BOOL isSuccess, NSString * _Nullable msg) {
  143. [self liveConversationJoin];
  144. }];
  145. }
  146. else {
  147. [self liveConversationJoin];
  148. }
  149. }
  150. - (void)liveConversationJoin {
  151. [[V2TIMManager sharedInstance] joinGroup:self.roomId msg:nil succ:^{
  152. dispatch_async(dispatch_get_main_queue(), ^{
  153. [self addConstMessage];
  154. [self sendWelcomeMessage];
  155. [self getGroupAttrInfo];
  156. [self getGroupCount];
  157. });
  158. } fail:^(int code, NSString *desc) {
  159. NSLog(@"");
  160. }];
  161. }
  162. - (void)getGroupAttrInfo {
  163. [[V2TIMManager sharedInstance] getGroupAttributes:self.roomId keys:nil succ:^(NSMutableDictionary<NSString *,NSString *> *groupAttributeList) {
  164. NSLog(@"");
  165. [self evaluateGroupInfo:groupAttributeList];
  166. } fail:^(int code, NSString *desc) {
  167. }];
  168. }
  169. - (void)getGroupCount {
  170. [[V2TIMManager sharedInstance] getGroupCounters:self.roomId keys:nil succ:^(NSDictionary<NSString *,NSNumber *> *groupCounters) {
  171. NSLog(@"");
  172. [self evaluateGroupCount:groupCounters];
  173. } fail:^(int code, NSString *desc) {
  174. }];
  175. }
  176. - (void)addConstMessage {
  177. TXConstMessage *statement = [[TXConstMessage alloc] init];
  178. statement.userInfo = [self getCurrentUser];
  179. statement.text = @"欢迎进入直播课堂,请遵守相关法规,禁止传播低俗、暴力等不良信息。为孩子创造健康绿色的学习环境。";
  180. [self appendAndDisplayMessage:statement];
  181. }
  182. - (void)sendWelcomeMessage {
  183. TXLiveMessageWelcome *welcomeMessage = [[TXLiveMessageWelcome alloc] init];
  184. welcomeMessage.userInfo = [self getCurrentUser];
  185. MJWeakSelf;
  186. [self sendCustomMessage:welcomeMessage priority:V2TIM_PRIORITY_DEFAULT displayMessage:NO callback:^(BOOL success) {
  187. weakSelf.hasSendWelcomeMessage = YES;
  188. [weakSelf showEnterMessageAndJoinRoom];
  189. }];
  190. }
  191. - (void)showEnterMessageAndJoinRoom {
  192. NSString *contentString = [NSString stringWithFormat:@"%@ 进入直播间",UserDefault(NicknameKey)];
  193. [self showAnimationView:YES showMessag:contentString];
  194. }
  195. - (void)joinLiveRoom {
  196. [self changeEmptyStatusView];
  197. [self resetNetTips];
  198. [self startPlay];
  199. }
  200. - (void)viewWillAppear:(BOOL)animated {
  201. [super viewWillAppear:animated];
  202. [UIApplication sharedApplication].idleTimerDisabled = YES;
  203. [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
  204. [IQKeyboardManager sharedManager].enable = NO;
  205. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
  206. // 重新渲染view
  207. KSDragWindowManager *manager = [KSDragWindowManager sharedManager];
  208. if (manager.hasShowWindow) {
  209. [manager resignDragWindow];
  210. }
  211. if (self.hasShowSuspendView) {
  212. [self.videoView addSubview:self.videoRenderView];
  213. [self.videoRenderView mas_updateConstraints:^(MASConstraintMaker *make) {
  214. make.left.right.bottom.top.mas_equalTo(self.videoView);
  215. }];
  216. _hasShowSuspendView = NO;
  217. }
  218. if (self.bottomView.isMute == NO) {
  219. [self muteVoiceAction];
  220. }
  221. }
  222. - (void)viewWillDisappear:(BOOL)animated {
  223. [super viewWillDisappear:animated];
  224. [UIApplication sharedApplication].idleTimerDisabled = NO;
  225. if (self.landScape) {
  226. [self changeOrientation:NO];
  227. }
  228. [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
  229. [IQKeyboardManager sharedManager].enable = YES;
  230. if (@available(iOS 13.0, *)) {
  231. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
  232. } else {
  233. // Fallback on earlier versions
  234. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
  235. }
  236. }
  237. - (void)defaultConfig {
  238. self.enableChat = YES;
  239. self.enableSeat = YES;
  240. self.enableLike = YES;
  241. self.needSwitchButton = NO;
  242. self.micStatus = MICSTATUS_NOMAL;
  243. self.isCreateInRoom = NO; // 默认主讲人不在房间
  244. self.blacklistFlag = NO;
  245. self.isCloseRoom = NO;
  246. self.lastClickPraiseTime = 0;
  247. self.isAudience = YES;
  248. self.isCreaterVideoEnable = YES;
  249. }
  250. - (void)viewDidLoad {
  251. [super viewDidLoad];
  252. // Do any additional setup after loading the view.
  253. self.ks_prefersNavigationBarHidden = YES;
  254. [self setupUI];
  255. [self registerNotification];
  256. [self joinChatRoom];
  257. [self joinLiveRoom];
  258. [self notiferJoinSuccessToServiceCallback:^{
  259. }];
  260. }
  261. - (void)registerNotification {
  262. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMessageNotification:) name:OnReceiveTXLiveMessageNotification object:nil];
  263. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(liveroomLogOut) name:@"liveroomLogout" object:nil];
  264. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(liveroomQuit) name:@"liveroomQuit" object:nil];
  265. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(IMConnetedCallback) name:@"TXIMConnected" object:nil];
  266. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(muteAllAudio) name:@"muteLiveAudio" object:nil];
  267. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveGroupMessage:) name:OnReceiveTXLiveGroupNotification object:nil];
  268. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveGroupCountMessage:) name:OnReceiveTXLiveGroupCountNotification object:nil];
  269. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkTips) name:@"networkError" object:nil];
  270. }
  271. - (void)networkTips {
  272. [self MBPShow:@"直播已断开,请检查您的网络"];
  273. self.isConnectedFailed = YES;
  274. }
  275. - (void)IMConnetedCallback {
  276. self.isConnectedFailed = NO;
  277. dispatch_main_async_safe(^{
  278. // IM 连接成功回调
  279. if (self.hasSendWelcomeMessage) { // 如果已经发送了进入消息
  280. // 查询是否直播间开启
  281. [LiveModuleService imLiveBroadcastRoomQueryRoomRequest:KS_GET roomId:self.roomId success:^(NSDictionary * _Nonnull dic) {
  282. if ([dic ks_integerValueForKey:@"code"] == 200 && [dic ks_boolValueForKey:@"status"]) {
  283. // 回调信息
  284. MJWeakSelf;
  285. [self notiferJoinSuccessToServiceCallback:^{
  286. [weakSelf sendWelcomeMessage];
  287. [weakSelf checkPlayerStatus];
  288. }];
  289. }
  290. else {
  291. [self MBPShow:MESSAGEKEY];
  292. [self quitRoom];
  293. }
  294. } faliure:^(NSError * _Nonnull error) {
  295. }];
  296. // 查询群属性
  297. [self getGroupAttrInfo];
  298. }
  299. });
  300. }
  301. - (void)checkPlayerStatus {
  302. if (self.isCloseRoom) {
  303. return;
  304. }
  305. if (self.isAudience) {
  306. if (self.livePlayer.isPlaying == NO) {
  307. [self resetNetTips];
  308. [self startPlay];
  309. }
  310. }
  311. else {
  312. [self connectHostWithStatus:NO];
  313. }
  314. }
  315. - (void)liveroomLogOut {
  316. [self MBPShow:@"该账号在其他设备上登录"];
  317. [self quitRoom];
  318. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  319. [[NSNotificationCenter defaultCenter] postNotificationName:@"backLoginView" object:nil];
  320. });
  321. }
  322. - (void)liveroomQuit {
  323. [self quitRoom];
  324. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  325. [[NSNotificationCenter defaultCenter] postNotificationName:@"backLoginView" object:nil];
  326. });
  327. }
  328. - (void)muteAllAudio {
  329. [self muteVoiceAction];
  330. }
  331. #pragma mark ----- // 观众上下麦
  332. - (void)connectHostWithStatus:(BOOL)isConnect {
  333. // 如果直播结束 不转换身份
  334. if (self.isCloseRoom == YES) {
  335. return;
  336. }
  337. // 转换中,不再处理转换身份
  338. if (self.isTransferRole) {
  339. return;
  340. }
  341. if (isConnect && self.isAudience == NO) {
  342. self.micStatus = MICSTATUS_CONNECTING;
  343. return;
  344. }
  345. else if (isConnect == NO && self.isAudience) {
  346. self.micStatus = MICSTATUS_NOMAL;
  347. return;
  348. }
  349. self.isTransferRole = YES;
  350. self.micEnable = YES;
  351. // 清理当前视图
  352. [self removeSeatContainer];
  353. self.remoteMemberArray = [NSMutableArray array];
  354. // 移除状态视图
  355. if (isConnect) {
  356. [self stopPlay];
  357. [self hideTipsView];
  358. if (self.isCreaterVideoEnable) {
  359. [self hideEmptyView];
  360. }
  361. self.isAudience = NO;
  362. [self enterLiveRTCRoom];
  363. self.isTransferRole = NO;
  364. self.micStatus = MICSTATUS_CONNECTING;
  365. }
  366. else {
  367. self.isAudience = YES;
  368. if (self.isPauseLive == NO) {
  369. [self startPlay];
  370. }
  371. if (_trtcCloud) {
  372. [self.trtcCloud stopAllRemoteView];
  373. [self.trtcCloud stopLocalAudio];
  374. [self.trtcCloud exitRoom];
  375. _trtcCloud = nil;
  376. [TRTCCloud destroySharedIntance];
  377. }
  378. self.micStatus = MICSTATUS_NOMAL;
  379. self.isTransferRole = NO;
  380. }
  381. [self muteVoiceAction];
  382. }
  383. - (void)setupUI {
  384. self.view.backgroundColor = HexRGB(0x25292e);
  385. [self.view addSubview:self.emptyView];
  386. [self.view addSubview:self.endView];
  387. [self.view addSubview:self.videoContainerView];
  388. [self.videoContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
  389. make.left.right.top.bottom.mas_equalTo(self.view);
  390. }];
  391. [self.videoContainerView addSubview:self.videoView];
  392. // 异常的view
  393. [self.videoContainerView addSubview:self.netBadView];
  394. // 按钮和视频的布局
  395. if (self.needSwitchButton) {
  396. [self.videoView mas_makeConstraints:^(MASConstraintMaker *make) {
  397. make.left.right.mas_equalTo(self.videoContainerView);
  398. if (@available(iOS 11.0, *)) {
  399. make.top.mas_equalTo(self.videoContainerView.mas_safeAreaLayoutGuideTop).offset(160);
  400. } else {
  401. // Fallback on earlier versions
  402. make.top.mas_equalTo(self.videoContainerView.mas_top).offset(160);
  403. }
  404. CGFloat rate = 9 / 16.0f;
  405. make.height.mas_equalTo(self.videoContainerView.mas_width).multipliedBy(rate);
  406. make.width.height.mas_equalTo(self.videoContainerView).priorityLow();
  407. make.width.height.lessThanOrEqualTo(self.videoContainerView);
  408. }];
  409. // 显示切换按钮
  410. [self.videoContainerView addSubview:self.switchButton];
  411. [self.switchButton mas_makeConstraints:^(MASConstraintMaker *make) {
  412. make.right.mas_equalTo(self.videoContainerView.mas_right).offset(-10);
  413. make.width.height.mas_equalTo(33);
  414. make.bottom.mas_equalTo(self.videoView.mas_bottom).offset(-10);
  415. }];
  416. self.switchButton.hidden = NO;
  417. }
  418. else {
  419. [self.videoView mas_makeConstraints:^(MASConstraintMaker *make) {
  420. make.left.top.bottom.right.mas_equalTo(self.videoContainerView);
  421. }];
  422. }
  423. // 添加视频预览图
  424. [self.videoView addSubview:self.videoRenderView];
  425. [self.videoRenderView mas_makeConstraints:^(MASConstraintMaker *make) {
  426. make.left.right.top.bottom.mas_equalTo(self.videoView);
  427. }];
  428. [self.emptyView mas_makeConstraints:^(MASConstraintMaker *make) {
  429. make.left.right.top.bottom.mas_equalTo(self.videoView);
  430. }];
  431. self.emptyView.hidden = YES;
  432. // 直播结束的画面
  433. [self.endView mas_makeConstraints:^(MASConstraintMaker *make) {
  434. make.left.right.top.bottom.mas_equalTo(self.videoView);
  435. }];
  436. self.endView.hidden = YES;
  437. [self.netBadView mas_makeConstraints:^(MASConstraintMaker *make) {
  438. make.left.right.top.bottom.mas_equalTo(self.videoView);
  439. }];
  440. self.netBadView.hidden = YES;
  441. [self.videoContainerView addSubview:self.headView];
  442. self.headView.boardcastName.text = [NSString returnNoNullStringWithString:self.createrName];
  443. if (![NSString isEmptyString:self.createrAvatal]) {
  444. [self.headView.boardcastAvatal sd_setImageWithURL:[NSURL URLWithString:[self.createrAvatal getUrlEndcodeString]] placeholderImage:[UIImage imageNamed:@"teacher_logo"]];
  445. }
  446. [self countLikeMessageCount];
  447. [self countMemberCount];
  448. [self.headView mas_makeConstraints:^(MASConstraintMaker *make) {
  449. make.left.right.mas_equalTo(self.videoContainerView);
  450. make.height.mas_equalTo(80);
  451. if (@available(iOS 11.0, *)) {
  452. make.top.mas_equalTo(self.videoContainerView.mas_safeAreaLayoutGuideTop).offset(0);
  453. } else {
  454. // Fallback on earlier versions
  455. make.top.mas_equalTo(self.videoContainerView.mas_top).offset(0);
  456. }
  457. }];
  458. // 聊天区域
  459. [self.videoContainerView addSubview:self.messageContentView];
  460. if (self.hideCartButton == NO) {
  461. [self.videoContainerView addSubview:self.animationView];
  462. [self.animationView mas_makeConstraints:^(MASConstraintMaker *make) {
  463. if (@available(iOS 11.0, *)) {
  464. make.bottom.mas_equalTo(self.videoContainerView.mas_safeAreaLayoutGuideBottom).offset(-9);
  465. } else {
  466. // Fallback on earlier versions
  467. make.bottom.mas_equalTo(self.videoContainerView.mas_bottom).offset(-9);
  468. }
  469. make.centerX.mas_equalTo(self.videoContainerView.mas_right).offset(-80);
  470. make.width.mas_equalTo(48);
  471. make.height.mas_equalTo(56);
  472. }];
  473. [self.animationView play];
  474. }
  475. [self.videoContainerView addSubview:self.bottomView];
  476. self.bottomView.hideCartVButton = self.hideCartButton;
  477. [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
  478. make.left.right.mas_equalTo(self.videoContainerView);
  479. if (@available(iOS 11.0, *)) {
  480. make.bottom.mas_equalTo(self.videoContainerView.mas_safeAreaLayoutGuideBottom).offset(-5);
  481. } else {
  482. // Fallback on earlier versions
  483. make.bottom.mas_equalTo(self.videoContainerView.mas_bottom).offset(-5);
  484. }
  485. make.height.mas_equalTo(44);
  486. }];
  487. // 聊天页面
  488. if (self.needSwitchButton) {
  489. [self.messageContentView mas_makeConstraints:^(MASConstraintMaker *make) {
  490. make.left.mas_equalTo(self.videoContainerView.mas_left);
  491. make.right.mas_equalTo(self.videoContainerView.mas_right);
  492. make.bottom.mas_equalTo(self.bottomView.mas_top).offset(-5);
  493. make.top.mas_equalTo(self.videoView.mas_bottom).offset(10).priorityLow();
  494. }];
  495. }
  496. else {
  497. [self.messageContentView mas_makeConstraints:^(MASConstraintMaker *make) {
  498. make.left.mas_equalTo(self.videoContainerView.mas_left);
  499. make.right.mas_equalTo(self.videoContainerView.mas_right);
  500. make.bottom.mas_equalTo(self.bottomView.mas_top).offset(-10);
  501. make.height.mas_equalTo(180);
  502. }];
  503. }
  504. [self.videoContainerView addSubview:self.inputBar];
  505. [_inputBar setBackgroundColor: [UIColor whiteColor]];
  506. [_inputBar setFrame:CGRectMake(0, KPortraitHeight, KPortraitWidth , 50)];
  507. [_inputBar setHidden:YES];
  508. [self.messageContentView addSubview:self.conversationMessageTableView];
  509. [self.conversationMessageTableView mas_makeConstraints:^(MASConstraintMaker *make) {
  510. make.left.top.mas_equalTo(self.messageContentView);
  511. make.width.mas_equalTo(KPortraitWidth);
  512. make.bottom.mas_equalTo(self.messageContentView.mas_bottom);
  513. }];
  514. UITapGestureRecognizer *resetBottomTapGesture =[[UITapGestureRecognizer alloc]
  515. initWithTarget:self
  516. action:@selector(resetBottomGesture:)];
  517. resetBottomTapGesture.delegate = self;
  518. [self.videoContainerView addGestureRecognizer:resetBottomTapGesture];
  519. UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headViewAnimation:)];
  520. tapGesture.delegate = self;
  521. [self.videoView addGestureRecognizer:tapGesture];
  522. }
  523. - (void)headViewAnimation:(UIGestureRecognizer *)gestureRecognizer {
  524. if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
  525. [self setDefaultBottomViewStatus];
  526. }
  527. if (self.landScape) {
  528. self.isHiddenHeadView = !self.isHiddenHeadView;
  529. }
  530. }
  531. #pragma mark -- 加入直播间和退出直播间回到服务
  532. - (void)notiferJoinSuccessToServiceCallback:(void(^)(void))callback {
  533. [LiveModuleService LiveroomJoinRequest:KS_GET roomId:self.roomId success:^(NSDictionary * _Nonnull dic) {
  534. NSTimeInterval enterTime = [dic ks_integerValueForKey:@"data"];
  535. self.enterTime = enterTime;
  536. NSDate *currentDate = [NSDate date];
  537. self.enterDate = currentDate;
  538. callback();
  539. } faliure:^(NSError * _Nonnull error) {
  540. callback();
  541. }];
  542. }
  543. - (void)quitNotiferService {
  544. NSDate *currentDate = [NSDate date];
  545. NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:self.enterDate];
  546. NSInteger time = (NSInteger)(timeInterval *1000);
  547. if (self.enterTime > 0) {
  548. time = self.enterTime + time;
  549. }
  550. else {
  551. time = (NSInteger)([currentDate timeIntervalSince1970] *1000);
  552. }
  553. [LiveModuleService LiveroomQuit:KS_POST time:time success:^(NSDictionary * _Nonnull dic) {
  554. if ([dic ks_integerValueForKey:@"errCode"] == 0) {
  555. NSLog(@"success");
  556. }
  557. else {
  558. NSLog(@"----- error %@", [dic ks_stringValueForKey:@"errMsg"]);
  559. }
  560. } faliure:^(NSError * _Nonnull error) {
  561. }];
  562. }
  563. #pragma mark ------ 播放控制
  564. - (void)startPlay {
  565. if ([self.livePlayer isPlaying] == NO) {
  566. [self resetNetTips];
  567. if (self.isCreaterVideoEnable) {
  568. [self hideEmptyView];
  569. }
  570. [self showLoading];
  571. self.videoRenderView.hasMainStream = YES;
  572. self.videoRenderView.hasSubStream = NO;
  573. [self.livePlayer setRenderView:self.videoRenderView.mainView];
  574. if (self.needSwitchButton) {
  575. [self.livePlayer setRenderFillMode:V2TXLiveFillModeFit];
  576. }
  577. else {
  578. [self.livePlayer setRenderFillMode:V2TXLiveFillModeFill];
  579. }
  580. // 获取url的方法
  581. NSString *streamId = [NSString stringWithFormat:@"%@_%@", self.roomId, self.createrId];
  582. NSString *url = [TXLiveURLUtils generateRtmpPlayUrl:streamId playDomain:self.playDomain liveUrlKey:self.liveUrlKey];
  583. [self.livePlayer startLivePlay:url];
  584. [self muteVoiceAction];
  585. }
  586. }
  587. - (void)stopPlay {
  588. if (_livePlayer) {
  589. if ([self.livePlayer isPlaying]) {
  590. [self hideLoading];
  591. [self.livePlayer stopPlay];
  592. }
  593. }
  594. }
  595. // 不播放声音
  596. - (void)pauserAudio {
  597. [self.livePlayer pauseAudio];
  598. }
  599. // 恢复声音
  600. - (void)resumeAudio {
  601. [self.livePlayer resumeAudio];
  602. }
  603. #pragma mark ---- V2TXLivePlayerObserver
  604. - (void)onError:(id<V2TXLivePlayer>)player code:(V2TXLiveCode)code message:(NSString *)msg extraInfo:(NSDictionary *)extraInfo {
  605. if (code == V2TXLIVE_ERROR_DISCONNECTED) {
  606. // 连接断开
  607. if (self.isPauseLive == NO && self.isCreateInRoom) {
  608. [self hideLoading];
  609. [self showBadNetTips];
  610. }
  611. }
  612. else if (code == V2TXLIVE_WARNING_VIDEO_BLOCK) {
  613. }
  614. NSLog(@"---- V2TXLivePlayer %zd message:%@", code, msg);
  615. }
  616. - (void)onConnected:(id<V2TXLivePlayer>)player extraInfo:(NSDictionary *)extraInfo {
  617. NSLog(@" ------ connected %@", extraInfo);
  618. self.isPauseLive = NO;
  619. self.isCreateInRoom = YES;
  620. if (self.isCreaterVideoEnable) {
  621. [self hideEmptyView];
  622. }
  623. }
  624. - (void)onVideoPlaying:(id<V2TXLivePlayer>)player firstPlay:(BOOL)firstPlay extraInfo:(NSDictionary *)extraInfo {
  625. NSLog(@" ------ onVideoPlaying %@", extraInfo);
  626. [self hideLoading];
  627. }
  628. - (void)onVideoResolutionChanged:(id<V2TXLivePlayer>)player width:(NSInteger)width height:(NSInteger)height {
  629. NSLog(@" ------ onVideoResolutionChanged %zd %zd", width, height);
  630. }
  631. // 直播状态
  632. - (void)onStatisticsUpdate:(id<V2TXLivePlayer>)player statistics:(V2TXLivePlayerStatistics *)statistics {
  633. NSLog(@"----- V2TXLivePlayerStatistics desc %@", statistics.description);
  634. }
  635. - (void)onReceiveSeiMessage:(id<V2TXLivePlayer>)player payloadType:(int)payloadType data:(NSData *)data {
  636. NSLog(@"----- onReceiveSeiMessage desc %@", [data mj_JSONObject]);
  637. if (self.isAudience == YES && self.isPauseLive == NO) {
  638. NSDictionary *parm = [data mj_JSONObject];
  639. if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"sync"]) { // 同步连麦人数
  640. NSArray *memberArray = [parm ks_arrayValueForKey:@"seatUser"];
  641. NSMutableArray *remoteSeatArray = [NSMutableArray arrayWithArray:memberArray];
  642. // 移除自己
  643. NSMutableArray *seatArray = [NSMutableArray array];
  644. for (NSDictionary *userParm in remoteSeatArray) {
  645. if (![[userParm ks_stringValueForKey:@"userId"] isEqualToString:UserDefault(IM_USERID)]) {
  646. TXUISeatMember *member = [[TXUISeatMember alloc] init];
  647. member.userId = [userParm ks_stringValueForKey:@"userId"];
  648. member.muteMic = [userParm ks_boolValueForKey:@"micStatus"];
  649. [seatArray addObject:member];
  650. }
  651. }
  652. [self refreshSeatWithMember:seatArray];
  653. // if (self.remoteMemberArray.count != seatArray.count) { // 如果连麦人数不同
  654. // [self refreshSeatWithMember:seatArray];
  655. // }
  656. // else {
  657. // BOOL isSameUser = YES;
  658. // NSMutableArray *seatMemberArr = [self.remoteMemberArray mutableCopy];
  659. //
  660. // for (TXUISeatMember *member in seatMemberArr) {
  661. //
  662. // if (![remoteSeatArray containsObject:member]) {
  663. // isSameUser = NO;
  664. // }
  665. // }
  666. // if (isSameUser == NO) {
  667. // [self refreshSeatWithMember:seatArray];
  668. // }
  669. // }
  670. }
  671. }
  672. else {
  673. [self refreshSeatWithMember:@[]];
  674. }
  675. }
  676. - (void)refreshSeatWithMember:(NSArray *)memberArray {
  677. self.remoteMemberArray = [NSMutableArray arrayWithArray:memberArray];
  678. [self renderSeatView];
  679. }
  680. #pragma mark --- trtcCloud delegate
  681. // 远端主播加入房间
  682. - (void)onRemoteUserEnterRoom:(NSString *)userId {
  683. if (![self judgeContainerRemoteUser:userId] && ![userId isEqualToString:self.createrId]) { // 如果不包含当前用户 添加 和刷新连麦
  684. TXUISeatMember *member = [[TXUISeatMember alloc] init];
  685. member.userId = userId;
  686. member.muteMic = YES;
  687. [self.remoteMemberArray addObject:member];
  688. }
  689. [self renderSeatView];
  690. }
  691. // 远端主播离开
  692. - (void)onRemoteUserLeaveRoom:(NSString *)userId reason:(NSInteger)reason {
  693. if ([self judgeContainerRemoteUser:userId]) { // 如果包含当前用户 移除当前用和刷新连麦
  694. [self removeMemberUserId:userId];
  695. }
  696. [self renderSeatView];
  697. }
  698. - (BOOL)judgeContainerRemoteUser:(NSString *)userId {
  699. BOOL containUser = NO;
  700. NSMutableArray *remoteMemArray = [self.remoteMemberArray mutableCopy];
  701. for (TXUISeatMember *member in remoteMemArray) {
  702. if ([member.userId isEqualToString:userId]) {
  703. containUser = YES;
  704. }
  705. }
  706. return containUser;
  707. }
  708. - (void)removeMemberUserId:(NSString *)userId {
  709. NSMutableArray *remoteMemArray = [self.remoteMemberArray mutableCopy];
  710. for (TXUISeatMember *member in remoteMemArray) {
  711. if ([member.userId isEqualToString:userId]) {
  712. [self.remoteMemberArray removeObject:member];
  713. return;
  714. }
  715. }
  716. }
  717. - (void)onWarning:(TXLiteAVWarning)warningCode warningMsg:(NSString *)warningMsg extInfo:(NSDictionary *)extInfo {
  718. NSLog(@" warningMsg %@ extInfo:%@", warningMsg, extInfo.description);
  719. }
  720. // 远端视频
  721. - (void)onUserVideoAvailable:(NSString *)userId available:(BOOL)available {
  722. NSLog(@"creater remote videoStream status: %d", available);
  723. if (available) {
  724. self.videoRenderView.hasMainStream = YES;
  725. if (self.videoRenderView.hasSubStream) {
  726. [self.trtcCloud startRemoteView:self.createrId streamType:TRTCVideoStreamTypeBig view:self.videoRenderView.smallView];
  727. [self.trtcCloud startRemoteView:self.createrId streamType:TRTCVideoStreamTypeSub view:self.videoRenderView.mainView];
  728. }
  729. else {
  730. [self.trtcCloud stopRemoteView:self.createrId streamType:TRTCVideoStreamTypeSub];
  731. [self.trtcCloud startRemoteView:self.createrId streamType:TRTCVideoStreamTypeBig view:self.videoRenderView.mainView];
  732. }
  733. }
  734. else {
  735. self.videoRenderView.hasMainStream = NO;
  736. [self.trtcCloud stopRemoteView:self.createrId streamType:TRTCVideoStreamTypeBig];
  737. }
  738. }
  739. - (void)onUserSubStreamAvailable:(NSString *)userId available:(BOOL)available {
  740. NSLog(@"creater remote subStream status: %d", available);
  741. if (available) {
  742. self.videoRenderView.hasSubStream = YES;
  743. [self.trtcCloud startRemoteView:self.createrId streamType:TRTCVideoStreamTypeSub view:self.videoRenderView.mainView];
  744. if (self.videoRenderView.hasMainStream) {
  745. [self.trtcCloud startRemoteView:self.createrId streamType:TRTCVideoStreamTypeBig view:self.videoRenderView.smallView];
  746. }
  747. }
  748. else {
  749. self.videoRenderView.hasSubStream = NO;
  750. [self.trtcCloud stopRemoteView:self.createrId streamType:TRTCVideoStreamTypeSub];
  751. if (self.videoRenderView.hasMainStream) {
  752. [self.trtcCloud startRemoteView:self.createrId streamType:TRTCVideoStreamTypeBig view:self.videoRenderView.mainView];
  753. }
  754. }
  755. }
  756. - (void)onFirstVideoFrame:(NSString *)userId streamType:(TRTCVideoStreamType)streamType width:(int)width height:(int)height {
  757. }
  758. - (void)onRecvSEIMsg:(NSString *)userId message:(NSData *)message {
  759. // NSDictionary *parm = [message mj_JSONObject];
  760. }
  761. - (void)onUserAudioAvailable:(NSString *)userId available:(BOOL)available {
  762. for (TXUISeatMember *member in self.remoteMemberArray) {
  763. if ([member.userId isEqualToString:userId]) {
  764. member.muteMic = !available;
  765. }
  766. }
  767. [self renderSeatView];
  768. }
  769. #pragma mark - gesture and button action
  770. - (void)resetBottomGesture:(UIGestureRecognizer *)gestureRecognizer {
  771. if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
  772. [self setDefaultBottomViewStatus];
  773. }
  774. }
  775. - (void)setDefaultBottomViewStatus {
  776. [self.inputBar setInputBarStatus:KSBottomBarStatusDefault];
  777. [self.inputBar setHidden:YES];
  778. }
  779. #pragma mark --- setter
  780. - (void)setIsHiddenHeadView:(BOOL)isHiddenHeadView {
  781. if (_isHiddenHeadView == isHiddenHeadView) {
  782. return;
  783. }
  784. _isHiddenHeadView = isHiddenHeadView;
  785. //告知需要更改约束
  786. [self.view setNeedsUpdateConstraints];
  787. [UIView animateWithDuration:0.5 animations:^{
  788. if (isHiddenHeadView) {
  789. [self.headView mas_updateConstraints:^(MASConstraintMaker *make) {
  790. if (@available(iOS 11.0, *)) {
  791. make.top.mas_equalTo(self.videoContainerView.mas_safeAreaLayoutGuideTop).offset(-80);
  792. } else {
  793. // Fallback on earlier versions
  794. make.top.mas_equalTo(self.videoContainerView.mas_top).offset(-80);
  795. }
  796. }];
  797. }
  798. else {
  799. [self.headView mas_updateConstraints:^(MASConstraintMaker *make) {
  800. if (@available(iOS 11.0, *)) {
  801. make.top.mas_equalTo(self.videoContainerView.mas_safeAreaLayoutGuideTop).offset(10);
  802. } else {
  803. // Fallback on earlier versions
  804. make.top.mas_equalTo(self.videoContainerView.mas_top).offset(10);
  805. }
  806. }];
  807. }
  808. [self.headView.superview layoutIfNeeded];
  809. }];
  810. }
  811. #pragma mark ----- landscape action
  812. - (void)transferToLandscape {
  813. [self setDefaultBottomViewStatus];
  814. [self changeOrientation:!self.landScape];
  815. }
  816. - (void)changeOrientation:(BOOL)isLandScape {
  817. self.landScape = isLandScape;
  818. if (isLandScape) {
  819. // 切换到横屏
  820. AppDelegate* delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
  821. delegate.allowAutoRotate = YES;
  822. [UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight inController:self];
  823. }
  824. else {
  825. AppDelegate* delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
  826. delegate.allowAutoRotate = NO;
  827. [UIDevice switchNewOrientation:UIInterfaceOrientationPortrait inController:self];
  828. }
  829. self.isHiddenHeadView = NO;
  830. [self updateConstraint];
  831. }
  832. - (void)updateConstraint {
  833. if (self.landScape) {
  834. self.bottomView.hideChatView = YES;
  835. self.messageContentView.hidden = YES;
  836. self.headView.hideQuitButton = YES;
  837. [self.videoView mas_remakeConstraints:^(MASConstraintMaker *make) {
  838. if (IS_IPAD) {
  839. make.left.right.mas_equalTo(self.videoContainerView);
  840. make.centerX.mas_equalTo(self.videoContainerView.mas_centerX);
  841. CGFloat rate = 9 / 16.0f;
  842. make.height.mas_equalTo(self.videoContainerView.mas_width).multipliedBy(rate);
  843. make.width.height.mas_equalTo(self.videoContainerView).priorityLow();
  844. make.width.height.lessThanOrEqualTo(self.videoContainerView);
  845. }
  846. else {
  847. make.top.bottom.mas_equalTo(self.videoContainerView);
  848. make.centerX.mas_equalTo(self.videoContainerView.mas_centerX);
  849. // 宽高设置
  850. CGFloat rate = 16 / 9.0f;
  851. make.width.mas_equalTo(self.videoContainerView.mas_height).multipliedBy(rate);
  852. make.width.height.mas_equalTo(self.videoContainerView).priorityLow();
  853. make.width.height.lessThanOrEqualTo(self.videoContainerView);
  854. }
  855. }];
  856. [self.switchButton mas_remakeConstraints:^(MASConstraintMaker *make) {
  857. make.right.mas_equalTo(self.videoContainerView.mas_right).offset(-10);
  858. make.width.height.mas_equalTo(33);
  859. make.centerY.mas_equalTo(self.videoView.mas_centerY);
  860. }];
  861. }
  862. else {
  863. self.bottomView.hideChatView = NO;
  864. self.messageContentView.hidden = NO;
  865. self.headView.hideQuitButton = NO;
  866. [self.videoView mas_remakeConstraints:^(MASConstraintMaker *make) {
  867. make.left.right.mas_equalTo(self.videoContainerView);
  868. if (@available(iOS 11.0, *)) {
  869. make.top.mas_equalTo(self.videoContainerView.mas_safeAreaLayoutGuideTop).offset(160);
  870. } else {
  871. // Fallback on earlier versions
  872. make.top.mas_equalTo(self.videoContainerView.mas_top).offset(160);
  873. }
  874. CGFloat rate = 9 / 16.0f;
  875. make.height.mas_equalTo(self.videoContainerView.mas_width).multipliedBy(rate);
  876. make.width.height.mas_equalTo(self.videoContainerView).priorityLow();
  877. make.width.height.lessThanOrEqualTo(self.videoContainerView);
  878. }];
  879. [self.switchButton mas_remakeConstraints:^(MASConstraintMaker *make) {
  880. make.right.mas_equalTo(self.videoContainerView.mas_right).offset(-10);
  881. make.width.height.mas_equalTo(33);
  882. make.bottom.mas_equalTo(self.videoView.mas_bottom).offset(-10);
  883. }];
  884. }
  885. // 更新连麦UI
  886. if ([self.videoContainerView.subviews containsObject:self.seatContainer]) {
  887. [self updateSeatContainerConstraint];
  888. }
  889. }
  890. - (void)showEmptyViewDisplay:(BOOL)isPublish {
  891. NSString *imageName = @"";
  892. NSString *descMessage = @"";
  893. if (isPublish) {
  894. imageName = @"liveVideo_close";
  895. descMessage = @"主讲人已关闭画面!";
  896. }
  897. else {
  898. imageName = @"liveroom_empty";
  899. descMessage = @"休息一下,马上回来!";
  900. }
  901. [self.emptyView configViewWithImageName:imageName desc:descMessage];
  902. [self hideTipsView];
  903. self.videoView.hidden = YES;
  904. self.emptyView.hidden = NO;
  905. }
  906. - (void)hideEmptyView {
  907. self.emptyView.hidden = YES;
  908. self.videoView.hidden = NO;
  909. }
  910. - (void)changeEmptyStatusView {
  911. if (self.isCloseRoom == NO) { // 只有在非结束直播状态下
  912. if (self.isPauseLive) { // 暂停直播
  913. [self showEmptyViewDisplay:NO];
  914. }
  915. else { // 如果未暂停直播
  916. if (self.isCreaterVideoEnable) { // 如果摄像头开启
  917. [self hideTipsView];
  918. [self hideEmptyView];
  919. }
  920. else { // 主播关闭了摄像头
  921. [self showEmptyViewDisplay:YES];
  922. }
  923. }
  924. }
  925. }
  926. - (void)renderSeatView {
  927. NSMutableArray *seatArray = [NSMutableArray array];
  928. NSArray *remoteUserArray = [self.remoteMemberArray mutableCopy];
  929. for (TXUISeatMember *member in remoteUserArray) {
  930. [seatArray addObject:member];
  931. }
  932. BOOL isContainSelf = NO;
  933. for (TXUISeatMember *member in seatArray) {
  934. if ([member.userId isEqualToString:UserDefault(IM_USERID)]) {
  935. isContainSelf = YES;
  936. break;
  937. }
  938. }
  939. if (self.micStatus == MICSTATUS_CONNECTING && !isContainSelf) {
  940. TXUISeatMember *currentMember = [[TXUISeatMember alloc] init];
  941. currentMember.userId = UserDefault(IM_USERID);
  942. currentMember.muteMic = !self.micEnable;
  943. [seatArray addObject:currentMember];
  944. }
  945. NSLog(@"-- seat member--- %zd -", seatArray.count);
  946. if (seatArray.count) {
  947. if (![self.videoContainerView.subviews containsObject:self.seatContainer]) {
  948. [self.videoContainerView addSubview:self.seatContainer];
  949. }
  950. [self updateSeatContainerConstraint];
  951. // self.seatContainer.seatMemberArray = [NSMutableArray arrayWithArray:seatArray];
  952. // [self.seatContainer refreshSeatUI];
  953. [self.seatContainer refreshSeatUIWithMember:[NSMutableArray arrayWithArray:seatArray]];
  954. }
  955. else {
  956. [self removeSeatContainer];
  957. }
  958. }
  959. // 移除连麦视图
  960. - (void)removeSeatContainer {
  961. if ([self.videoContainerView.subviews containsObject:self.seatContainer]) {
  962. [self.seatContainer removeFromSuperview];
  963. }
  964. }
  965. - (void)updateSeatContainerConstraint {
  966. if (self.landScape) {
  967. [self.seatContainer mas_remakeConstraints:^(MASConstraintMaker *make) {
  968. if (@available(iOS 11.0, *)) {
  969. make.left.mas_equalTo(self.videoContainerView.mas_safeAreaLayoutGuideLeft);
  970. } else {
  971. // Fallback on earlier versions
  972. make.left.mas_equalTo(self.videoContainerView.mas_left);
  973. }
  974. make.right.mas_equalTo(self.videoContainerView.mas_right).offset(-70);
  975. if (@available(iOS 11.0, *)) {
  976. make.top.mas_equalTo(self.videoContainerView.mas_safeAreaLayoutGuideTop).offset(85);
  977. } else {
  978. // Fallback on earlier versions
  979. make.top.mas_equalTo(self.videoContainerView.mas_top).offset(85);
  980. }
  981. make.height.mas_equalTo(70);
  982. }];
  983. }
  984. else {
  985. [self.seatContainer mas_remakeConstraints:^(MASConstraintMaker *make) {
  986. make.left.right.mas_equalTo(self.videoContainerView);
  987. make.top.mas_equalTo(self.headView.mas_bottom).offset(0);
  988. make.height.mas_equalTo(70);
  989. }];
  990. }
  991. }
  992. #pragma mark ----- 加入TRC房间
  993. - (void)enterLiveRTCRoom {
  994. self.videoRenderView.hasMainStream = NO;
  995. self.videoRenderView.hasSubStream = NO;
  996. TRTCParams *parms = [[TRTCParams alloc] init];
  997. parms.sdkAppId = CONFIG_TXSDKAPPID;
  998. parms.userSig = self.UserSig;
  999. parms.role = TRTCRoleAnchor;
  1000. parms.strRoomId = self.roomId;
  1001. parms.userId = UserDefault(IM_USERID);
  1002. self.trtcCloud.delegate = self;
  1003. [self config3AParams];
  1004. [self configVideoAndAudioSetting];
  1005. [self.trtcCloud enterRoom:parms appScene:TRTCAppSceneLIVE];
  1006. TRTCRenderParams *rendParams = [[TRTCRenderParams alloc] init];
  1007. if (self.needSwitchButton) {
  1008. rendParams.fillMode = TRTCVideoFillMode_Fit;
  1009. }
  1010. else {
  1011. rendParams.fillMode = TRTCVideoFillMode_Fill;
  1012. }
  1013. [self.trtcCloud setRemoteRenderParams:self.createrId streamType:TRTCVideoStreamTypeBig params:rendParams];
  1014. [self.trtcCloud setRemoteRenderParams:self.createrId streamType:TRTCVideoStreamTypeSub params:rendParams];
  1015. }
  1016. - (void)configVideoAndAudioSetting {
  1017. [self.trtcCloud startLocalAudio:TRTCAudioQualityMusic];
  1018. TRTCVideoEncParam *videoEncParam = [[TRTCVideoEncParam alloc] init];
  1019. videoEncParam.videoFps = 24;
  1020. videoEncParam.resMode = TRTCVideoResolutionModePortrait;
  1021. videoEncParam.videoResolution = TRTCVideoResolution_960_540;
  1022. [self.trtcCloud setVideoEncoderParam:videoEncParam];
  1023. if (self.muteRoomMic) {
  1024. [self micButtonAction:self.muteRoomMic];
  1025. }
  1026. }
  1027. // 配置3A参数
  1028. - (void)config3AParams {
  1029. [self configANSParm:self.ANS];
  1030. [self configAECParm:self.AEC];
  1031. [self configAGCParm:self.AGC];
  1032. }
  1033. // 背景音抑制
  1034. - (void)configANSParm:(NSInteger)number {
  1035. NSMutableDictionary *dic = [NSMutableDictionary dictionary];
  1036. [dic setValue:@"enableAudioANS" forKey:@"api"];
  1037. NSMutableDictionary *subDic = [NSMutableDictionary dictionary];
  1038. if (number > 0) {
  1039. [subDic setValue:@(1) forKey:@"enable"];
  1040. [subDic setValue:@(number) forKey:@"level"];
  1041. }
  1042. else {
  1043. [subDic setValue:@(0) forKey:@"enable"];
  1044. [subDic setValue:@(0) forKey:@"level"];
  1045. }
  1046. [dic setValue:subDic forKey:@"params"];
  1047. NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:kNilOptions error:nil];
  1048. NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  1049. [self.trtcCloud callExperimentalAPI:jsonString];
  1050. }
  1051. // 回声消除
  1052. - (void)configAECParm:(NSInteger)number {
  1053. NSMutableDictionary *dic = [NSMutableDictionary dictionary];
  1054. [dic setValue:@"enableAudioAEC" forKey:@"api"];
  1055. NSMutableDictionary *subDic = [NSMutableDictionary dictionary];
  1056. if (number > 0) {
  1057. [subDic setValue:@(1) forKey:@"enable"];
  1058. [subDic setValue:@(number) forKey:@"level"];
  1059. }
  1060. else {
  1061. [subDic setValue:@(0) forKey:@"enable"];
  1062. [subDic setValue:@(0) forKey:@"level"];
  1063. }
  1064. [dic setValue:subDic forKey:@"params"];
  1065. NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:kNilOptions error:nil];
  1066. NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  1067. [self.trtcCloud callExperimentalAPI:jsonString];
  1068. }
  1069. // 自动增益
  1070. - (void)configAGCParm:(NSInteger)number {
  1071. NSMutableDictionary *dic = [NSMutableDictionary dictionary];
  1072. [dic setValue:@"enableAudioAGC" forKey:@"api"];
  1073. NSMutableDictionary *subDic = [NSMutableDictionary dictionary];
  1074. if (number > 0) {
  1075. [subDic setValue:@(1) forKey:@"enable"];
  1076. [subDic setValue:@(number) forKey:@"level"];
  1077. }
  1078. else {
  1079. [subDic setValue:@(0) forKey:@"enable"];
  1080. [subDic setValue:@(0) forKey:@"level"];
  1081. }
  1082. [dic setValue:subDic forKey:@"params"];
  1083. NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:kNilOptions error:nil];
  1084. NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  1085. [self.trtcCloud callExperimentalAPI:jsonString];
  1086. }
  1087. #pragma mark -------- live message handle
  1088. - (NSString *)getMsgClassName:(NSString *)messageObjectName {
  1089. TXLiveMessageModel *configModel = [[TXLiveMessageModel alloc] init];
  1090. NSString *className = [configModel getMessageClassName:messageObjectName];
  1091. return className;
  1092. }
  1093. /**
  1094. * 接收到消息的回调
  1095. */
  1096. - (void)didReceiveMessageNotification:(NSNotification *)notification {
  1097. NSDictionary *dic = notification.object; /// __block TXLiveMessageModel *liveMessage
  1098. NSDictionary *content = [dic ks_dictionaryValueForKey:@"message"];
  1099. NSString *objectName = [content ks_stringValueForKey:@"objectName"];
  1100. NSString *className = [self getMsgClassName:objectName];
  1101. __block TXLiveMessageModel *message = [[NSClassFromString(className) alloc] init];
  1102. message.messageId = [dic ks_stringValueForKey:@"msgID"];
  1103. message.groupId = [dic ks_stringValueForKey:@"groupID"];
  1104. [message evaluateSource:content];
  1105. if ([message.groupId isEqualToString:self.roomId]) {
  1106. __weak typeof(&*self) __blockSelf = self;
  1107. dispatch_async(dispatch_get_main_queue(), ^{
  1108. if ([message isMemberOfClass:[TXLiveMessageLike class]]) {
  1109. TXLiveMessageLike *likeMessage = (TXLiveMessageLike *)message;
  1110. NSLog(@"receive like count ------- %d",likeMessage.counts);
  1111. return;
  1112. }
  1113. else if ([message isMemberOfClass:[TXLiveMessageLikeCount class]]) {
  1114. return;
  1115. }
  1116. else if ([message isMemberOfClass:[TXLiveMessageWelcome class]]) {
  1117. TXLiveMessageWelcome *welcomeMessage = (TXLiveMessageWelcome *)message;
  1118. // 过滤自己发送的欢迎消息
  1119. if ([welcomeMessage.userInfo.sendUserId isEqualToString:UserDefault(IM_USERID)]) {
  1120. return;
  1121. }
  1122. if ([welcomeMessage.userInfo.sendUserId isEqual:__blockSelf.createrId]) { // 如果是老师 重置连麦申请状态
  1123. [__blockSelf resetMicWaitToNomal];
  1124. __blockSelf.isCreateInRoom = YES;
  1125. }
  1126. NSString *userName = [welcomeMessage.userInfo.sendUserName stringByAppendingString:@""];
  1127. NSString *contentMsg = [NSString stringWithFormat:@"%@ 进入直播间",userName];
  1128. [__blockSelf showAnimationView:YES showMessag:contentMsg];
  1129. return;
  1130. }
  1131. // 用户退出消息
  1132. else if ([message isMemberOfClass:[TXLiveMessageLeave class]]) {
  1133. // TXLiveMessageLeave *userLeaveMsg = (TXLiveMessageLeave *)message;
  1134. // if ([userLeaveMsg.userInfo.sendUserId isEqualToString:__blockSelf.createrId]) {
  1135. // __blockSelf.isCreateInRoom = NO;
  1136. // // 下麦
  1137. // if (__blockSelf.micStatus == MICSTATUS_CONNECTING) {
  1138. // [__blockSelf downSeatAction];
  1139. // }
  1140. // }
  1141. return;
  1142. }
  1143. // 用户退出回调
  1144. else if ([message isMemberOfClass:[TXLiveMessageUserQuit class]]) {
  1145. // TXLiveMessageUserQuit *userLeaveMsg = (TXLiveMessageUserQuit *)message;
  1146. // if ([userLeaveMsg.targetId isEqualToString:__blockSelf.createrId]) {
  1147. // __blockSelf.isCreateInRoom = NO;
  1148. // // 下麦
  1149. // if (__blockSelf.micStatus == MICSTATUS_CONNECTING) {
  1150. // [__blockSelf downSeatAction];
  1151. // }
  1152. // }
  1153. return;
  1154. }
  1155. else if ([message isMemberOfClass:[TXLiveMessageMemberUp class]]) {
  1156. return;
  1157. }
  1158. else if ([message isMemberOfClass:[TXLiveMessageStatSync class]]) { // 数据同步 不取点赞数
  1159. return;
  1160. }
  1161. else if ([message isMemberOfClass:[TXLiveMessageKickOut class]]) {
  1162. TXLiveMessageKickOut *kickMessage = (TXLiveMessageKickOut *)message;
  1163. NSString *currentUserId = UserDefault(IM_USERID);
  1164. if ([kickMessage.targetId isEqualToString:currentUserId]) {
  1165. __blockSelf.micStatus = MICSTATUS_NOMAL;
  1166. [__blockSelf kickOutLiveRoom];
  1167. }
  1168. return;
  1169. }
  1170. // 禁言控制
  1171. else if ([message isMemberOfClass:[TXLiveMessageChatBan class]]) {
  1172. TXLiveMessageChatBan *banMessage = (TXLiveMessageChatBan *)message;
  1173. if (banMessage.chatBan) { // 禁止发言
  1174. __blockSelf.enableChat = NO;
  1175. }
  1176. else { // 开启发言
  1177. __blockSelf.enableChat = YES;
  1178. }
  1179. [__blockSelf insertMessage:banMessage];
  1180. }
  1181. // 连麦控制消息
  1182. else if ([message isMemberOfClass:[TXLiveMessageSeatControl class]]) {
  1183. TXLiveMessageSeatControl *seatControlMessage = (TXLiveMessageSeatControl *)message;
  1184. if (seatControlMessage.seatBan) { // 禁止连麦
  1185. __blockSelf.enableSeat = NO;
  1186. // 未连麦情况下才重置
  1187. if (__blockSelf.micStatus != MICSTATUS_CONNECTING) {
  1188. // 如果在申请 发送取消申请消息
  1189. if (__blockSelf.micStatus == MICSTATUS_WAITING) {
  1190. [__blockSelf sendSeatMessageApply:NO];
  1191. }
  1192. __blockSelf.micStatus = MICSTATUS_NOMAL;
  1193. }
  1194. [__blockSelf hideApplyView];
  1195. [__blockSelf hideApplyingView];
  1196. }
  1197. else { // 开启连麦
  1198. __blockSelf.enableSeat = YES;
  1199. }
  1200. [__blockSelf insertMessage:seatControlMessage];
  1201. }
  1202. else if ([message isMemberOfClass:[TXLiveMessageSeatApply class]]) {
  1203. // 只处理主讲人发起的连麦邀请或取消操作
  1204. TXLiveMessageSeatApply *seatApplyMessage = (TXLiveMessageSeatApply *)message;
  1205. NSLog(@"----- RCChatroomSeatApply type:%ld audienceName:%@ ",seatApplyMessage.type,seatApplyMessage.audienceName);
  1206. // 只处理和自己相关的消息
  1207. if (![seatApplyMessage.audienceId isEqualToString:UserDefault(IM_USERID)]) {
  1208. // 刷新麦序
  1209. return;
  1210. }
  1211. if (seatApplyMessage.type == SEATHANDLE_INVITE) { // 主讲人发起申请
  1212. NSString *titles = [NSString stringWithFormat:@"%@邀请您连麦",[NSString returnNoNullStringWithString:seatApplyMessage.teacherName]];
  1213. [__blockSelf showInviteAlertMessage:titles];
  1214. }
  1215. else if (seatApplyMessage.type == SEATHANDLE_DISINVITE) { // 主讲人撤回申请
  1216. [__blockSelf MBPShow:@"主讲人撤回了连麦申请"];
  1217. [__blockSelf closeAlertView];
  1218. if (__blockSelf.micStatus == MICSTATUS_CONNECTING) {
  1219. [__blockSelf downSeatAction];
  1220. }
  1221. }
  1222. else if (seatApplyMessage.type == SEATHANDLE_KICKSEAT) { // 主讲人断开连麦
  1223. [__blockSelf kickSeatWithMessage:@"主讲人断开连麦"];
  1224. }
  1225. [__blockSelf hideApplyingView];
  1226. [__blockSelf insertMessage:seatApplyMessage];
  1227. }
  1228. else if ([message isMemberOfClass:[TXLiveMessageSeatResponse class]]) { // 只处理主讲人的回应
  1229. TXLiveMessageSeatResponse *seatResponseMessage = (TXLiveMessageSeatResponse *)message;
  1230. NSLog(@"----- RCChatroomSeatResponse type:%ld audienceName:%@ ",seatResponseMessage.type,seatResponseMessage.audienceName);
  1231. if (![seatResponseMessage.audienceId isEqualToString:UserDefault(IM_USERID)]) { // 只处理和自己相关的消息
  1232. return;
  1233. }
  1234. if (seatResponseMessage.type == SEATRESPONSE_TEACHERAPPROVE && __blockSelf.micStatus == MICSTATUS_WAITING) { //
  1235. [__blockSelf hideApplyingView];
  1236. [__blockSelf connectHostWithStatus:YES];
  1237. [__blockSelf insertMessage:seatResponseMessage];
  1238. }
  1239. else if (seatResponseMessage.type == SEATRESPONSE_TEACHERREJECT) {
  1240. [__blockSelf MBPShow:@"主讲人拒绝了您的连麦申请"];
  1241. // 处理连麦状态
  1242. [__blockSelf connectHostWithStatus:NO];
  1243. [__blockSelf insertMessage:seatResponseMessage];
  1244. }
  1245. }
  1246. else if ([message isMemberOfClass:[TXLiveMessageDownSeat class]]) { // 成员主动下麦消息
  1247. return;
  1248. }
  1249. else if ([message isMemberOfClass:[TXLiveMessageClose class]]) { // 直播间已关闭
  1250. [__blockSelf MBPShow:@"直播已结束"];
  1251. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1252. // 显示直播间关闭状态
  1253. [__blockSelf closeAlertView];
  1254. [__blockSelf displayCloseView];
  1255. [__blockSelf hideApplyingView];
  1256. });
  1257. return;
  1258. }
  1259. else if ([message isMemberOfClass:[TXLiveTextMessage class]]) {
  1260. TXLiveTextMessage *textMessage = (TXLiveTextMessage *)message;
  1261. [__blockSelf insertMessage:textMessage];
  1262. }
  1263. else if ([message isMemberOfClass:[TXLiveMessageCardMessage class]]) {
  1264. TXLiveMessageCardMessage *cardMessage = (TXLiveMessageCardMessage *)message;
  1265. [__blockSelf sendCardMessage:cardMessage.goodsContent];
  1266. }
  1267. else if ([message isMemberOfClass:[TXLiveMessagePauseLive class]]) { // 主讲人暂停直播
  1268. // __blockSelf.isPauseLive = YES;
  1269. // if (__blockSelf.micStatus == MICSTATUS_WAITING) {
  1270. // [__blockSelf sendSeatMessageApply:NO];
  1271. // }
  1272. // [__blockSelf resetNetTips];
  1273. // [__blockSelf resetConnectionStatus];
  1274. // [__blockSelf closeAlertView];
  1275. // [__blockSelf hideApplyingView];
  1276. // [__blockSelf changeEmptyStatusView];
  1277. // [__blockSelf closePlayStatus];
  1278. return;
  1279. }
  1280. else if ([message isMemberOfClass:[TXLiveMessageOpenLive class]]) { // 开始直播
  1281. // __blockSelf.isPauseLive = NO;
  1282. // __blockSelf.isCreateInRoom = YES;
  1283. // [__blockSelf resetNetTips];
  1284. // [__blockSelf hideEmptyView];
  1285. // [__blockSelf startPlay];
  1286. return;
  1287. }
  1288. else if ([message isMemberOfClass:[TXLiveMessageShopRush class]]) { //
  1289. TXLiveMessageShopRush *rushMsg = (TXLiveMessageShopRush *)message;
  1290. NSString *contentMsg = [NSString stringWithFormat:@"%@ 正在抢购",[NSString returnNoNullStringWithString:rushMsg.userInfo.sendUserName]];
  1291. [__blockSelf showAnimationView:NO showMessag:contentMsg];
  1292. }
  1293. else if ([message isMemberOfClass:[TXLiveMessageBlockUser class]]) { // 黑名单
  1294. TXLiveMessageBlockUser *blockMessage = (TXLiveMessageBlockUser *)message;
  1295. if ([blockMessage.userId isEqualToString:UserDefault(IM_USERID)]) {
  1296. __blockSelf.blacklistFlag = YES;
  1297. [__blockSelf resetConnectionStatus];
  1298. }
  1299. }
  1300. else if ([message isMemberOfClass:[TXLiveMessageUnBlockUser class]]) {
  1301. TXLiveMessageUnBlockUser *unBlockMessage = (TXLiveMessageUnBlockUser *)message;
  1302. if ([unBlockMessage.userId isEqualToString:UserDefault(IM_USERID)]) {
  1303. __blockSelf.blacklistFlag = NO;
  1304. }
  1305. }
  1306. else if ([message isMemberOfClass:[TXLiveMessageDownSeatAll class]]) { // 所有麦上用户下麦
  1307. TXLiveMessageDownSeatAll *downSeatMessage = (TXLiveMessageDownSeatAll *)message;
  1308. if (__blockSelf.micStatus == MICSTATUS_CONNECTING) {
  1309. [__blockSelf kickSeatWithMessage:@"主讲人断开连麦"];
  1310. [__blockSelf insertMessage:downSeatMessage];
  1311. }
  1312. }
  1313. else if ([message isMemberOfClass:[TXLiveMessageRejectAllSeat class]]) { // 拒绝所有连麦申请
  1314. TXLiveMessageRejectAllSeat *rejectAllMessage = (TXLiveMessageRejectAllSeat *)message;
  1315. if (__blockSelf.micStatus == MICSTATUS_WAITING) {
  1316. [__blockSelf MBPShow:@"主讲人拒绝了您的连麦申请"];
  1317. // 处理连麦状态
  1318. __blockSelf.micStatus = MICSTATUS_NOMAL;
  1319. [__blockSelf insertMessage:rejectAllMessage];
  1320. [__blockSelf hideApplyingView];
  1321. }
  1322. }
  1323. else if ([message isMemberOfClass:[TXControlMemberMic class]]) { // 控制学生麦克风
  1324. TXControlMemberMic *micCtrlMsg = (TXControlMemberMic *)message;
  1325. // 如果是控制当前学生的mic
  1326. if ([micCtrlMsg.userId isEqualToString:UserDefault(IM_USERID)]) {
  1327. [__blockSelf changeCurrentMicStatus:micCtrlMsg.muteMic];
  1328. }
  1329. }
  1330. else if ([message isMemberOfClass:[TXLiveForceKickMsg class]]) {
  1331. TXLiveForceKickMsg *changeMsg = (TXLiveForceKickMsg *)message;
  1332. if (changeMsg.targetIds.count == 0 || changeMsg.targetIds == nil) { // 如果是全员
  1333. [__blockSelf courseChangeTips:changeMsg];
  1334. }
  1335. else {
  1336. for (NSString *userId in changeMsg.targetIds) { // 如果部分学员中包含自己
  1337. if ([userId isEqualToString:UserDefault(IM_USERID)]) {
  1338. [__blockSelf courseChangeTips:changeMsg];
  1339. break;
  1340. }
  1341. }
  1342. }
  1343. }
  1344. });
  1345. }
  1346. }
  1347. - (void)courseChangeTips:(TXLiveForceKickMsg *)msg {
  1348. // 显示直播间关闭状态
  1349. [self closeAlertView];
  1350. [self displayCloseView];
  1351. [self hideApplyingView];
  1352. // 退出房间
  1353. NSString *tipsMsg = [NSString isEmptyString:msg.reason] ? @"当前课程已调整,请退出直播间" : msg.reason;
  1354. MJWeakSelf;
  1355. self.closeAlert = [LiveRoomConfirmAlert liveroomAlertWithTitle:tipsMsg sureTitle:@"确定" inView:self.view confirm:^{
  1356. [weakSelf exitRoom];
  1357. [weakSelf.navigationController dismissViewControllerAnimated:YES completion:nil];
  1358. }];
  1359. }
  1360. - (void)changeCurrentMicStatus:(BOOL)isMute {
  1361. if (isMute == !self.micEnable) { // 如果麦克风状态和当前状态一致,剔除
  1362. return;
  1363. }
  1364. if (_trtcCloud && self.isAudience == NO) {
  1365. self.micEnable = !self.micEnable;
  1366. [self.trtcCloud muteLocalAudio:!self.micEnable];
  1367. NSString *desc = @"";
  1368. if (self.micEnable) {
  1369. desc = @"主讲人已将您的麦克风开启";
  1370. }
  1371. else {
  1372. desc = @"主讲人已将您的麦克风关闭";
  1373. }
  1374. [self MBPShow:desc];
  1375. [self syncMicStatus:!self.micEnable];
  1376. }
  1377. }
  1378. - (void)didReceiveGroupMessage:(NSNotification *)notification {
  1379. NSDictionary *dic = notification.object; /// __block TXLiveMessageModel *liveMessage
  1380. NSString *groupId = [dic ks_stringValueForKey:@"groupID"];
  1381. NSDictionary *content = [dic ks_dictionaryValueForKey:@"message"];
  1382. if ([groupId isEqualToString:self.roomId]) {
  1383. [self evaluateGroupInfo:content];
  1384. }
  1385. }
  1386. - (void)evaluateGroupInfo:(NSDictionary *)groupInfo {
  1387. // 主播在房间
  1388. if ([[groupInfo ks_stringValueForKey:@"LIVE_STATUS"] isEqualToString:@"ON"]) { // 直播中
  1389. self.isPauseLive = NO;
  1390. if (self.isAudience) {
  1391. [self startPlay];
  1392. }
  1393. }
  1394. else if ([[groupInfo ks_stringValueForKey:@"LIVE_STATUS"] isEqualToString:@"OFF"]) { // 暂停直播
  1395. self.isPauseLive = YES;
  1396. [self closePlayStatus];
  1397. }
  1398. // 摄像头状态
  1399. if ([[groupInfo ks_stringValueForKey:@"ANCHOR_CAMERA"] isEqualToString:@"OFF"]) {
  1400. self.isCreaterVideoEnable = NO;
  1401. }
  1402. else {
  1403. self.isCreaterVideoEnable = YES;
  1404. }
  1405. // 禁言状态
  1406. if ([[groupInfo ks_stringValueForKey:@"GLOBAL_BAN"] isEqualToString:@"ON"]) {
  1407. self.enableChat = NO;
  1408. }
  1409. else {
  1410. self.enableChat = YES;
  1411. }
  1412. // 在线人数
  1413. if ([[groupInfo allKeys] containsObject:@"MEMBER_ONLINE"]) {
  1414. self.totalCount = [groupInfo ks_integerValueForKey:@"MEMBER_ONLINE"];
  1415. [self countMemberCount];
  1416. }
  1417. [self changeEmptyStatusView];
  1418. // 主播全员闭麦状态
  1419. if ([[groupInfo allKeys] containsObject:@"ANCHOR_MIC"]) {
  1420. if ([[groupInfo ks_stringValueForKey:@"ANCHOR_MIC"] isEqualToString:@"ON"]) { // 禁麦
  1421. if (self.muteRoomMic == NO) {
  1422. self.muteRoomMic = YES;
  1423. }
  1424. }
  1425. else {
  1426. if (self.muteRoomMic == YES) {
  1427. self.muteRoomMic = NO;
  1428. }
  1429. }
  1430. }
  1431. else {
  1432. if (self.muteRoomMic == YES) {
  1433. self.muteRoomMic = NO;
  1434. }
  1435. }
  1436. // 禁止连麦
  1437. if ([[groupInfo allKeys] containsObject:@"BAN_LINK_MIC"]) {
  1438. if ([[groupInfo ks_stringValueForKey:@"BAN_LINK_MIC"] isEqualToString:@"ON"]) { // 禁止
  1439. self.enableSeat = NO;
  1440. }
  1441. else {
  1442. self.enableSeat = YES;
  1443. }
  1444. }
  1445. else {
  1446. self.enableSeat = YES;
  1447. }
  1448. }
  1449. - (void)setMuteRoomMic:(BOOL)muteRoomMic {
  1450. _muteRoomMic = muteRoomMic;
  1451. [self changeCurrentMicStatus:muteRoomMic];
  1452. }
  1453. // 群属性变更信息
  1454. - (void)didReceiveGroupCountMessage:(NSNotification *)notification {
  1455. NSDictionary *dic = notification.object; /// __block TXLiveMessageModel *liveMessage
  1456. NSString *groupId = [dic ks_stringValueForKey:@"groupID"];
  1457. NSDictionary *content = [dic ks_dictionaryValueForKey:@"message"];
  1458. if ([groupId isEqualToString:self.roomId]) {
  1459. [self evaluateGroupCount:content];
  1460. }
  1461. }
  1462. - (void)evaluateGroupCount:(NSDictionary *)groupCount {
  1463. // 点赞数据
  1464. if ([[groupCount allKeys] containsObject:@"LIKES"]) {
  1465. self.likeCount = [groupCount ks_integerValueForKey:@"LIKES"];
  1466. [self countLikeMessageCount];
  1467. }
  1468. }
  1469. - (void)closePlayStatus {
  1470. if (self.micStatus == MICSTATUS_WAITING) {
  1471. [self sendSeatMessageApply:NO];
  1472. }
  1473. [self resetNetTips];
  1474. [self resetConnectionStatus];
  1475. [self closeAlertView];
  1476. [self hideApplyingView];
  1477. if (self.isAudience) {
  1478. [self stopPlay];
  1479. }
  1480. else {
  1481. if (_trtcCloud) {
  1482. [self.trtcCloud stopAllRemoteView];
  1483. [self.trtcCloud stopLocalAudio];
  1484. [self.trtcCloud exitRoom];
  1485. }
  1486. }
  1487. }
  1488. - (void)kickOutLiveRoom {
  1489. [self MBPShow:@"您已被踢出直播间"];
  1490. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1491. [self quitRoom];
  1492. });
  1493. }
  1494. #pragma mark ------ message operation
  1495. - (void)resetConnectionStatus {
  1496. if (self.micStatus == MICSTATUS_CONNECTING) {
  1497. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1498. [self sendDownSeatMsg];
  1499. [self connectHostWithStatus:NO];
  1500. });
  1501. }
  1502. else {
  1503. self.micStatus = MICSTATUS_NOMAL;
  1504. [self removeSeatContainer];
  1505. }
  1506. }
  1507. - (void)resetMicWaitToNomal {
  1508. if (self.micStatus == MICSTATUS_WAITING) {
  1509. self.micStatus = MICSTATUS_NOMAL;
  1510. }
  1511. }
  1512. - (void)tipsTeacherLeaveRoom {
  1513. [self MBPShow:@"主讲人已离开房间"];
  1514. }
  1515. - (void)hideApplyView {
  1516. if (self.applyView.isShow) {
  1517. [self.applyView hideView];
  1518. }
  1519. }
  1520. - (void)hideApplyingView {
  1521. if (self.applyingView.isShow) {
  1522. [self.applyingView hideView];
  1523. }
  1524. }
  1525. - (void)closeAlertView {
  1526. if (self.alertView && self.alertView.isShow) {
  1527. if (self.alertView.isQuitAlert == NO) {
  1528. [self.alertView removeFromSuperview];
  1529. self.alertView = nil;
  1530. }
  1531. }
  1532. }
  1533. - (void)displayCloseView {
  1534. self.isCloseRoom = YES;
  1535. [self hideTipsView];
  1536. // 移除连麦视图
  1537. [self removeSeatContainer];
  1538. if (self.micStatus != MICSTATUS_NOMAL) {
  1539. self.micStatus = MICSTATUS_NOMAL;
  1540. if (_trtcCloud) {
  1541. [self.trtcCloud stopLocalAudio];
  1542. [self.trtcCloud exitRoom];
  1543. }
  1544. }
  1545. [self stopPlay];
  1546. self.videoView.hidden = YES;
  1547. self.endView.hidden = NO;
  1548. [self setDefaultBottomViewStatus];
  1549. [[NSNotificationCenter defaultCenter] postNotificationName:@"LiveroomClose" object:nil];
  1550. }
  1551. - (void)sendCardMessage:(NSArray *)content {
  1552. // if (_webContainer) {
  1553. // NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
  1554. // [sendParm setValue:@"cardChange" forKey:@"api"];
  1555. // [sendParm setValue:content forKey:@"content"];
  1556. // [self.webContainer postMessage:sendParm];
  1557. // }
  1558. }
  1559. - (void)showInviteAlertMessage:(NSString *)tipsMessage {
  1560. if (self.alertView && self.alertView.isShow) {
  1561. [self.alertView removeFromSuperview];
  1562. self.alertView = nil;
  1563. }
  1564. MJWeakSelf;
  1565. self.alertView = [LiveAlertView shareInstance];
  1566. [self.alertView alertWithTitle:@"连麦邀请" desc:tipsMessage leftButtonTitle:@"取消" rightTitle:@"确定" inView:self.view cancel:^{
  1567. weakSelf.micStatus = MICSTATUS_NOMAL;
  1568. [weakSelf sendSeatResponseMessage:NO];
  1569. } confirm:^{
  1570. [weakSelf sendSeatResponseMessage:YES];
  1571. }];
  1572. }
  1573. - (void)sendSeatResponseMessage:(BOOL)isApprove {
  1574. SEATRESPONSE type = isApprove ? SEATRESPONSE_AUDIENCEAPPROVE : SEATRESPONSE_AUDIENCEREJECT;
  1575. TXLiveMessageSeatResponse *responseMessage = [[TXLiveMessageSeatResponse alloc] init];
  1576. responseMessage.userInfo = [self getCurrentUser];
  1577. responseMessage.type = type;
  1578. responseMessage.audienceId = UserDefault(IM_USERID);
  1579. responseMessage.audienceName = UserDefault(NicknameKey);
  1580. MJWeakSelf;
  1581. [self sendCustomMessage:responseMessage priority:V2TIM_PRIORITY_HIGH displayMessage:YES callback:^(BOOL success) {
  1582. if (success) {
  1583. if (isApprove) {
  1584. [weakSelf connectHostWithStatus:YES];
  1585. }
  1586. }
  1587. }];
  1588. }
  1589. - (void)kickSeatWithMessage:(NSString *)message {
  1590. [self MBPShow:message];
  1591. [self sendDownSeatMsg];
  1592. [self connectHostWithStatus:NO];
  1593. }
  1594. - (void)insertMessage:(TXLiveMessageModel *)liveMessage {
  1595. [self appendAndDisplayMessage:liveMessage];
  1596. }
  1597. #pragma mark table data source
  1598. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  1599. return self.conversationDataRepository.count;
  1600. }
  1601. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  1602. TXLiveMessageModel *model = [self.conversationDataRepository objectAtIndex:indexPath.row];
  1603. TXLiveChatListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TXLiveChatListCell"];
  1604. if (!cell) {
  1605. cell = [[TXLiveChatListCell appearance] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TXLiveChatListCell"];
  1606. }
  1607. if ([model isMemberOfClass:[TXConstMessage class]] || [model isMemberOfClass:[TXLiveTextMessage class]] || [model isMemberOfClass:[TXLiveMessageWelcome class]] || [model isMemberOfClass:[TXLiveMessageLike class]] || [model isMemberOfClass:[TXLiveMessageSeatControl class]] ||[model isMemberOfClass:[TXLiveMessageChatBan class]] || [model isMemberOfClass:[TXLiveMessageSeatApply class]] || [model isMemberOfClass:[TXLiveMessageSeatResponse class]] || [model isMemberOfClass:[TXLiveMessageShopRush class]] || [model isMemberOfClass:[TXLiveMessageDownSeatAll class]] || [model isMemberOfClass:[TXLiveMessageRejectAllSeat class]] ){
  1608. [cell setDataModel:model createrId:self.createrId];
  1609. }
  1610. return cell;
  1611. }
  1612. #pragma mark ----- lazying
  1613. - (TRTCCloud *)trtcCloud {
  1614. if (!_trtcCloud) {
  1615. _trtcCloud = [TRTCCloud sharedInstance];
  1616. _trtcCloud.delegate = self;
  1617. }
  1618. return _trtcCloud;
  1619. }
  1620. - (V2TXLivePlayer *)livePlayer {
  1621. if (!_livePlayer) {
  1622. _livePlayer = [[V2TXLivePlayer alloc] init];
  1623. [_livePlayer enableReceiveSeiMessage:YES payloadType:243];
  1624. [_livePlayer setObserver:self];
  1625. }
  1626. return _livePlayer;
  1627. }
  1628. - (UIView *)videoContainerView {
  1629. if (!_videoContainerView) {
  1630. _videoContainerView = [[UIView alloc] initWithFrame:CGRectZero];
  1631. _videoContainerView.backgroundColor = [UIColor clearColor];
  1632. }
  1633. return _videoContainerView;
  1634. }
  1635. - (UIView *)videoView {
  1636. if (!_videoView) {
  1637. _videoView = [[UIView alloc] initWithFrame:CGRectZero];
  1638. _videoView.backgroundColor = HexRGB(0x1a1a1a);
  1639. }
  1640. return _videoView;
  1641. }
  1642. - (TXLiveVideoView *)videoRenderView {
  1643. if (!_videoRenderView) {
  1644. _videoRenderView = [[TXLiveVideoView alloc] initWithFrame:CGRectZero];
  1645. }
  1646. return _videoRenderView;
  1647. }
  1648. - (LiveRoomHeadView *)headView {
  1649. if (!_headView) {
  1650. _headView = [LiveRoomHeadView shareInstance];
  1651. MJWeakSelf;
  1652. [_headView quitAction:^{
  1653. [weakSelf showQuitAlert];
  1654. }];
  1655. }
  1656. return _headView;
  1657. }
  1658. - (void)showQuitAlert {
  1659. if (self.isCloseRoom) { // 如果直播结束 直接点击退出房间
  1660. [self quitRoom];
  1661. }
  1662. else if (self.micStatus == MICSTATUS_CONNECTING) {
  1663. [self quitAction];
  1664. }
  1665. else {
  1666. MJWeakSelf;
  1667. self.alertView = [LiveAlertView shareInstance];
  1668. self.alertView.isQuitAlert = YES;
  1669. [self.alertView alertWithTitle:@"确定要退出直播间吗?" desc:@"退出后如再次观看可重新进入~" leftButtonTitle:@"取消" rightTitle:@"确认" inView:self.view cancel:^{
  1670. } confirm:^{
  1671. [weakSelf quitAction];
  1672. }];
  1673. }
  1674. }
  1675. - (void)quitRoom {
  1676. KSDragWindowManager *manager = [KSDragWindowManager sharedManager];
  1677. if (manager.hasShowWindow) {
  1678. [manager resignDragWindow];
  1679. }
  1680. if (self.landScape) {
  1681. [self changeOrientation:!self.landScape];
  1682. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1683. // 退出房间
  1684. [self exitRoom];
  1685. [self.navigationController dismissViewControllerAnimated:YES completion:nil];
  1686. });
  1687. }
  1688. else {
  1689. // 退出房间
  1690. [self exitRoom];
  1691. [self.navigationController dismissViewControllerAnimated:YES completion:nil];
  1692. }
  1693. }
  1694. // 顶部退出房间
  1695. - (void)quitAction {
  1696. if (self.micStatus == MICSTATUS_CONNECTING) {
  1697. MJWeakSelf;
  1698. self.alertView = [LiveAlertView shareInstance];
  1699. [self.alertView alertWithTitle:@"提示" desc:@"连麦中,是否退出房间?" leftButtonTitle:@"取消" rightTitle:@"确定" inView:self.view cancel:^{
  1700. } confirm:^{
  1701. [weakSelf quitRoom];
  1702. }];
  1703. }
  1704. else {
  1705. [self quitRoom];
  1706. }
  1707. }
  1708. - (void)exitRoom {
  1709. if (self.isAudience) {
  1710. [self stopPlay];
  1711. }
  1712. else {
  1713. if (_trtcCloud) {
  1714. [self.trtcCloud stopLocalAudio];
  1715. [self.trtcCloud exitRoom];
  1716. }
  1717. }
  1718. TXLiveMessageLeave *leaveMsg = [[TXLiveMessageLeave alloc] init];
  1719. leaveMsg.userInfo = [self getCurrentUser];
  1720. MJWeakSelf;
  1721. [self sendCustomMessage:leaveMsg priority:V2TIM_PRIORITY_NORMAL displayMessage:NO callback:^(BOOL success) {
  1722. // quit 接口
  1723. [weakSelf quitNotiferService];
  1724. [weakSelf quitChatRoom];
  1725. }];
  1726. }
  1727. - (void)quitChatRoom {
  1728. [[V2TIMManager sharedInstance] quitGroup:self.roomId succ:^{
  1729. } fail:^(int code, NSString *desc) {
  1730. }];
  1731. }
  1732. - (LiveRoomBottomView *)bottomView {
  1733. if (!_bottomView) {
  1734. _bottomView = [LiveRoomBottomView shareInstance];
  1735. MJWeakSelf;
  1736. [_bottomView bottomClickAction:^(LIVEROOMACTION action) {
  1737. [weakSelf bottomViewAction:action];
  1738. }];
  1739. }
  1740. return _bottomView;
  1741. }
  1742. - (void)bottomViewAction:(LIVEROOMACTION)action {
  1743. if (self.isCloseRoom) {
  1744. [self MBPShow:@"直播已结束"];
  1745. return;
  1746. }
  1747. if (action == LIVEROOMACTION_CHAT) {
  1748. if (self.blacklistFlag == YES) {
  1749. [self MBPShow:@"您已被管理员禁言"];
  1750. return;
  1751. }
  1752. if (self.enableChat) { // 判断是否全员禁言
  1753. [_inputBar setHidden:NO];
  1754. [_inputBar setInputBarStatus:KSBottomBarStatusKeyboard];
  1755. }
  1756. else {
  1757. [self MBPShow:@"管理员关闭聊天"];
  1758. }
  1759. }
  1760. else if (action == LIVEROOMACTION_SEAT) { // 连麦按钮
  1761. // 判断是否是连麦状态
  1762. if (self.micStatus == MICSTATUS_CONNECTING) { // 连麦中
  1763. // 是否取消连麦
  1764. MJWeakSelf;
  1765. self.alertView = [LiveAlertView shareInstance];
  1766. [self.alertView alertWithTitle:@"连麦中,确认取消连麦吗?" desc:@"断开后如想再次连麦可重新发起" leftButtonTitle:@"取消" rightTitle:@"确定关闭" inView:self.view cancel:^{
  1767. } confirm:^{
  1768. [weakSelf downSeatAction];
  1769. }];
  1770. }
  1771. else if (self.micStatus == MICSTATUS_WAITING) { // 连麦申请中
  1772. // 弹窗取消申请
  1773. [self displayApplyingView];
  1774. }
  1775. else {
  1776. // 禁止聊天可以连麦(测试确认)
  1777. if (self.blacklistFlag == YES) {
  1778. [self MBPShow:@"您已被管理员禁言"];
  1779. return;
  1780. }
  1781. if (self.isPauseLive == YES) {
  1782. [self MBPShow:@"老师暂停中,暂时无法接受申请"];
  1783. return;
  1784. }
  1785. if (self.enableSeat) {
  1786. [self displaySeatApplyView];
  1787. }
  1788. else {
  1789. [self MBPShow:@"管理员关闭连麦申请"];
  1790. }
  1791. }
  1792. }
  1793. else if (action == LIVEROOMACTION_LIKE) { // 点赞
  1794. [self praiseBtnPressed];
  1795. }
  1796. else if (action == LIVEROOMACTION_SHOP) { // shop
  1797. [self showCartAlert];
  1798. }
  1799. else if (action == LIVEROOMACTION_MUTE) {
  1800. [self muteVoiceAction];
  1801. }
  1802. }
  1803. - (void)showCartAlert {
  1804. [self.cardView showViewInView:self.view];
  1805. }
  1806. - (void)downSeatAction {
  1807. [self sendDownSeatMsg];
  1808. [self connectHostWithStatus:NO];
  1809. }
  1810. - (void)sendDownSeatMsg {
  1811. TXLiveMessageDownSeat *downSeatMsg = [[TXLiveMessageDownSeat alloc] init];
  1812. TXLiveUser *mineInfo = [self getCurrentUser];
  1813. downSeatMsg.userInfo = mineInfo;
  1814. downSeatMsg.audienceId = mineInfo.sendUserId;
  1815. downSeatMsg.audienceName = mineInfo.sendUserName;
  1816. [self sendCustomMessage:downSeatMsg priority:V2TIM_PRIORITY_HIGH displayMessage:NO callback:^(BOOL success) {
  1817. }];
  1818. }
  1819. - (KSShopCardView *)cardView {
  1820. if (!_cardView) {
  1821. _cardView = [KSShopCardView shareInstance];
  1822. MJWeakSelf;
  1823. [_cardView clickAction:^(CART_TYPE type) {
  1824. [weakSelf displayTeacherInfo:type];
  1825. }];
  1826. }
  1827. return _cardView;
  1828. }
  1829. // tabs= practice | 陪练课 live | 直播课 video | 视频课 music | 乐谱 跳转到对应tab页
  1830. - (void)displayTeacherInfo:(CART_TYPE)type {
  1831. [self sendRushMessage];
  1832. if (self.isPauseLive == NO) {
  1833. _hasShowSuspendView = YES;
  1834. KSDragWindowManager *manager = [KSDragWindowManager sharedManager];
  1835. BOOL isPhoneLive = self.needSwitchButton ? NO : YES;
  1836. [manager initDragWindowWithPhoneLive:isPhoneLive];
  1837. manager.rootVC = (CustomNavViewController *)self.navigationController;
  1838. [self.videoRenderView removeFromSuperview];
  1839. [manager.dragWindow.containerView addSubview:self.videoRenderView];
  1840. [self.videoRenderView mas_updateConstraints:^(MASConstraintMaker *make) {
  1841. make.left.right.top.bottom.mas_equalTo(manager.dragWindow.containerView);
  1842. }];
  1843. [manager.dragWindow bringSubviewToFront:manager.dragWindow.cancelButton];
  1844. }
  1845. NSString *tabs = @"";
  1846. switch (type) {
  1847. case CART_TYPE_NONE:
  1848. {
  1849. tabs = @"";
  1850. }
  1851. break;
  1852. case CART_TYPE_ACCOMPANY:
  1853. {
  1854. tabs = @"practice";
  1855. }
  1856. break;
  1857. case CART_TYPE_LIVE:
  1858. {
  1859. tabs = @"live";
  1860. }
  1861. break;
  1862. case CART_TYPE_VIDEO:
  1863. {
  1864. tabs = @"video";
  1865. }
  1866. break;
  1867. case CART_TYPE_MUSIC:
  1868. {
  1869. tabs = @"music";
  1870. }
  1871. break;
  1872. default:
  1873. break;
  1874. }
  1875. NSString *url = @"";
  1876. if ([NSString isEmptyString:tabs]) {
  1877. url = [NSString stringWithFormat:@"%@%@%@", WEBHOST,@"/#/teacherHome?teacherId=",self.createrUserId];
  1878. }
  1879. else {
  1880. url = [NSString stringWithFormat:@"%@%@%@&tabs=%@", WEBHOST,@"/#/teacherHome?teacherId=",self.createrUserId,tabs];
  1881. }
  1882. KSLiveWebViewController *ctrl = [[KSLiveWebViewController alloc] init];
  1883. ctrl.url = url;
  1884. [self.navigationController pushViewController:ctrl animated:YES];
  1885. }
  1886. - (void)sendRushMessage {
  1887. TXLiveMessageShopRush *rushMessage = [[TXLiveMessageShopRush alloc] init];
  1888. rushMessage.userInfo = [self getCurrentUser];
  1889. [self sendCustomMessage:rushMessage priority:V2TIM_PRIORITY_DEFAULT displayMessage:NO callback:^(BOOL success) {
  1890. }];
  1891. }
  1892. - (void)toDetailView:(NSString *)linkUrl {
  1893. [self sendRushMessage];
  1894. if (self.isPauseLive == NO) {
  1895. _hasShowSuspendView = YES;
  1896. KSDragWindowManager *manager = [KSDragWindowManager sharedManager];
  1897. BOOL isPhoneLive = self.needSwitchButton ? NO : YES;
  1898. [manager initDragWindowWithPhoneLive:isPhoneLive];
  1899. manager.rootVC = (CustomNavViewController *)self.navigationController;
  1900. [self.videoRenderView removeFromSuperview];
  1901. [manager.dragWindow.containerView addSubview:self.videoRenderView];
  1902. [self.videoRenderView mas_updateConstraints:^(MASConstraintMaker *make) {
  1903. make.left.right.top.bottom.mas_equalTo(manager.dragWindow.containerView);
  1904. }];
  1905. [manager.dragWindow bringSubviewToFront:manager.dragWindow.cancelButton];
  1906. }
  1907. KSLiveWebViewController *ctrl = [[KSLiveWebViewController alloc] init];
  1908. ctrl.url = linkUrl;
  1909. [self.navigationController pushViewController:ctrl animated:YES];
  1910. }
  1911. - (void)muteVoiceAction {
  1912. if (self.bottomView.isMute) {
  1913. if ([self.livePlayer isPlaying]) {
  1914. [self.livePlayer setPlayoutVolume:0];
  1915. }
  1916. if (_trtcCloud) {
  1917. [self.trtcCloud muteAllRemoteAudio:YES];
  1918. }
  1919. }
  1920. else {
  1921. if ([self.livePlayer isPlaying]) {
  1922. [self.livePlayer setPlayoutVolume:100];
  1923. }
  1924. if (_trtcCloud) {
  1925. [self.trtcCloud muteAllRemoteAudio:NO];
  1926. }
  1927. }
  1928. }
  1929. - (KSLiveEmptyView *)emptyView {
  1930. if (!_emptyView) {
  1931. _emptyView = [[KSLiveEmptyView alloc] init];
  1932. BOOL isPhoneLive = self.needSwitchButton ? NO : YES;
  1933. [_emptyView dispPlayViewIsPhoneLive:isPhoneLive];
  1934. }
  1935. return _emptyView;
  1936. }
  1937. - (KSLiveEndView *)endView {
  1938. if (!_endView) {
  1939. _endView = [[KSLiveEndView alloc] init];
  1940. _endView.backgroundColor = HexRGB(0x25292e);
  1941. BOOL isPhoneLive = self.needSwitchButton ? NO : YES;
  1942. [_endView dispPlayViewIsPhoneLive:isPhoneLive];
  1943. }
  1944. return _endView;
  1945. }
  1946. - (KSLiveBadNetView *)netBadView {
  1947. if (!_netBadView) {
  1948. _netBadView = [[KSLiveBadNetView alloc] init];
  1949. BOOL isPhoneLive = self.needSwitchButton ? NO : YES;
  1950. [_netBadView dispPlayViewIsPhoneLive:isPhoneLive];
  1951. MJWeakSelf;
  1952. [_netBadView configViewWithImageName:@"liveVideo_close" desc:@"视频加载失败" callback:^{
  1953. [weakSelf resetAllConnection];
  1954. }];
  1955. }
  1956. return _netBadView;
  1957. }
  1958. - (void)resetNetTips {
  1959. [self hideTipsView];
  1960. }
  1961. - (void)showBadNetTips {
  1962. dispatch_main_async_safe(^{
  1963. if (self.isCloseRoom == NO) {
  1964. if (self.netBadView.hidden == YES) {
  1965. self.netBadView.hidden = NO;
  1966. self.videoView.hidden = YES;
  1967. }
  1968. }
  1969. });
  1970. }
  1971. - (void)hideTipsView {
  1972. dispatch_main_async_safe(^{
  1973. if (self.netBadView.hidden == NO) {
  1974. self.netBadView.hidden = YES;
  1975. self.videoView.hidden = NO;
  1976. }
  1977. })
  1978. }
  1979. // 黑名单
  1980. - (void)setBlacklistFlag:(BOOL)blacklistFlag {
  1981. _blacklistFlag = blacklistFlag;
  1982. [self refreshBottomChatStatus];
  1983. }
  1984. - (void)refreshBottomChatStatus {
  1985. if (self.bottomView) {
  1986. NSString *tipsTitle = self.blacklistFlag ? @"您已被管理员禁言" : @"快来互动吧!";
  1987. self.bottomView.tipsLabel.text = tipsTitle;
  1988. self.bottomView.tipsLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
  1989. }
  1990. }
  1991. - (void)resetAllConnection {
  1992. [self resetNetTips];
  1993. // 清理视图
  1994. [self hideEmptyView];
  1995. [self removeSeatContainer];
  1996. // 立刻房间后重新加入房间
  1997. [self startPlay];
  1998. }
  1999. - (LOTAnimationView *)animationView {
  2000. if (!_animationView) {
  2001. _animationView = [LOTAnimationView animationWithFilePath:[[NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"LiveCard" ofType:@"bundle"]] pathForResource:@"cardAnimation" ofType:@"json"]];
  2002. _animationView.loopAnimation = YES;
  2003. }
  2004. return _animationView;
  2005. }
  2006. - (UIButton *)switchButton {
  2007. if (!_switchButton) {
  2008. _switchButton = [UIButton buttonWithType:UIButtonTypeCustom];
  2009. [_switchButton setImage:[UIImage imageNamed:@"live_switch"] forState:UIControlStateNormal];
  2010. [_switchButton addTarget:self action:@selector(transferToLandscape) forControlEvents:UIControlEventTouchUpInside];
  2011. }
  2012. return _switchButton;
  2013. }
  2014. - (UIView *)messageContentView {
  2015. if (!_messageContentView) {
  2016. _messageContentView = [[UIView alloc] init];
  2017. [_messageContentView setBackgroundColor: [UIColor clearColor]];
  2018. }
  2019. return _messageContentView;
  2020. }
  2021. - (UITableView *)conversationMessageTableView {
  2022. if (!_conversationMessageTableView) {
  2023. _conversationMessageTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
  2024. _conversationMessageTableView.backgroundColor = [UIColor clearColor];
  2025. _conversationMessageTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  2026. _conversationMessageTableView.dataSource = self;
  2027. _conversationMessageTableView.delegate = self;
  2028. _conversationMessageTableView.rowHeight = UITableViewAutomaticDimension;
  2029. _conversationMessageTableView.estimatedRowHeight = 40.0f;
  2030. _conversationMessageTableView.showsVerticalScrollIndicator = NO;
  2031. [_conversationMessageTableView registerClass:[TXLiveChatListCell class] forCellReuseIdentifier:@"TXLiveChatListCell"];
  2032. }
  2033. return _conversationMessageTableView;
  2034. }
  2035. - (NSMutableArray<TXLiveMessageModel *> *)conversationDataRepository {
  2036. if (!_conversationDataRepository) {
  2037. _conversationDataRepository = [NSMutableArray array];
  2038. }
  2039. return _conversationDataRepository;
  2040. }
  2041. - (TXSeatContainerView *)seatContainer {
  2042. if (!_seatContainer) {
  2043. _seatContainer = [[TXSeatContainerView alloc] init];
  2044. MJWeakSelf;
  2045. [_seatContainer seatActionCallback:^(NSString * _Nonnull userId, BOOL muteMic) {
  2046. [weakSelf muteUserAction:userId muteStatus:muteMic];
  2047. }];
  2048. }
  2049. return _seatContainer;
  2050. }
  2051. - (void)muteUserAction:(NSString *)userId muteStatus:(BOOL)muteMic {
  2052. [self micButtonAction:muteMic];
  2053. TXMicStatusSync *ctrlMsg = [[TXMicStatusSync alloc] init];
  2054. ctrlMsg.userInfo = [self getCurrentUser];
  2055. ctrlMsg.userId = userId;
  2056. ctrlMsg.muteMic = muteMic;
  2057. [self sendCustomMessage:ctrlMsg priority:V2TIM_PRIORITY_HIGH displayMessage:NO callback:^(BOOL success) {
  2058. }];
  2059. }
  2060. - (KSChatInputBarControl *)inputBar {
  2061. if (!_inputBar) {
  2062. _inputBar = [[KSChatInputBarControl alloc] initWithStatus:KSBottomBarStatusDefault];
  2063. [_inputBar setDelegate:self];
  2064. }
  2065. return _inputBar;
  2066. }
  2067. - (void)setMicStatus:(MICSTATUS)micStatus {
  2068. _micStatus = micStatus;
  2069. if (self.bottomView) {
  2070. switch (micStatus) {
  2071. case MICSTATUS_NOMAL:
  2072. {
  2073. [self.bottomView.seatButton setImage:[UIImage imageNamed:@"seat_image"] forState:UIControlStateNormal];
  2074. }
  2075. break;
  2076. case MICSTATUS_WAITING:
  2077. {
  2078. [self.bottomView.seatButton setImage:[UIImage imageNamed:@"seat_connecting"] forState:UIControlStateNormal];
  2079. }
  2080. break;
  2081. case MICSTATUS_CONNECTING:
  2082. {
  2083. [self.bottomView.seatButton setImage:[UIImage imageNamed:@"seat_connected"] forState:UIControlStateNormal];
  2084. }
  2085. break;
  2086. default:
  2087. break;
  2088. }
  2089. }
  2090. }
  2091. #pragma mark ----- 人数和点赞数统计
  2092. - (void)countLikeMessageCount {
  2093. NSInteger count = self.likeCount;
  2094. NSString *desc = @"";
  2095. if (count > 10000) {
  2096. count = count / 10000;
  2097. desc = [NSString stringWithFormat:@"本场点赞%zd万+",count];
  2098. }
  2099. else {
  2100. desc = [NSString stringWithFormat:@"本场点赞%zd",count];
  2101. }
  2102. self.headView.likeCount.text = desc;
  2103. }
  2104. - (void)countMemberCount {
  2105. NSInteger count = self.totalCount;
  2106. NSString *desc = @"";
  2107. if (count > 10000) {
  2108. count = count / 10000;
  2109. desc = [NSString stringWithFormat:@"%zd万+人",count];
  2110. }
  2111. else {
  2112. desc = [NSString stringWithFormat:@"%zd人",count];
  2113. }
  2114. self.headView.roomMemberCount.text = desc;
  2115. }
  2116. /**
  2117. * 判断消息是否在collectionView的底部
  2118. *
  2119. * @return 是否在底部
  2120. */
  2121. - (BOOL)isAtTheBottomOfTableView {
  2122. if (self.conversationMessageTableView.contentSize.height <= self.conversationMessageTableView.frame.size.height) {
  2123. return YES;
  2124. }
  2125. if(self.conversationMessageTableView.contentOffset.y +200 >= (self.conversationMessageTableView.contentSize.height - self.conversationMessageTableView.frame.size.height)) {
  2126. return YES;
  2127. }else{
  2128. return NO;
  2129. }
  2130. }
  2131. /**
  2132. * 消息滚动到底部
  2133. *
  2134. * @param animated 是否开启动画效果
  2135. */
  2136. - (void)scrollToBottomAnimated:(BOOL)animated {
  2137. if ([self.conversationMessageTableView numberOfSections] == 0) {
  2138. return;
  2139. }
  2140. NSUInteger finalRow = MAX(0, [self.conversationMessageTableView numberOfRowsInSection:0] - 1);
  2141. if (0 == finalRow) {
  2142. return;
  2143. }
  2144. NSIndexPath *finalIndexPath =
  2145. [NSIndexPath indexPathForItem:finalRow inSection:0];
  2146. [self.conversationMessageTableView scrollToRowAtIndexPath:finalIndexPath atScrollPosition:UITableViewScrollPositionTop animated:animated];
  2147. }
  2148. #pragma mark ---- dealloc
  2149. - (void)dealloc {
  2150. NSLog(@"---- live room dealloc");
  2151. [[NSNotificationCenter defaultCenter] removeObserver:self];
  2152. if (_livePlayer) {
  2153. [self.livePlayer stopPlay];
  2154. _livePlayer = nil;
  2155. }
  2156. if (_trtcCloud) {
  2157. [self.trtcCloud stopAllRemoteView];
  2158. [self.trtcCloud stopLocalAudio];
  2159. [self.trtcCloud exitRoom];
  2160. _trtcCloud = nil;
  2161. [TRTCCloud destroySharedIntance];
  2162. }
  2163. }
  2164. #pragma mark - KSChatInputBarControlDelegate
  2165. // 根据inputBar 回调来修改页面布局
  2166. - (void)onInputBarControlContentSizeChanged:(CGRect)frame withAnimationDuration:(CGFloat)duration andAnimationCurve:(UIViewAnimationCurve)curve {
  2167. CGRect originFrame = _inputBar.frame;
  2168. __weak __typeof(&*self)weakSelf = self;
  2169. // 目前只使用y值即可 -- 只修改messageContentView高度,让展示消息view和输入框随之移动
  2170. [UIView animateWithDuration:duration animations:^{
  2171. [UIView setAnimationCurve:curve];
  2172. [weakSelf.inputBar setFrame:CGRectMake(0, frame.origin.y - originFrame.size.height, originFrame.size.width, originFrame.size.height)];
  2173. [UIView commitAnimations];
  2174. }];
  2175. }
  2176. // 发送消息
  2177. - (void)onTouchSendButton:(NSString *)text {
  2178. if (self.blacklistFlag == YES) {
  2179. [self setDefaultBottomViewStatus];
  2180. return;
  2181. }
  2182. NSDate *date = [NSDate date];
  2183. NSTimeInterval currentInterval = [date timeIntervalSince1970];
  2184. if (currentInterval - self.lastSendMsgTime < 3) {
  2185. [self MBPShow:@"您说话太快啦"];
  2186. return;
  2187. }
  2188. if (self.lastSendMsgTime == 0) {
  2189. self.lastSendMsgTime = currentInterval;
  2190. }
  2191. if (text.length > 40) {
  2192. [self MBPShow:@"聊天消息需在40个字以内哦"];
  2193. return;
  2194. }
  2195. if (self.enableChat) {
  2196. self.lastSendMsgTime = currentInterval;
  2197. [self touristSendMessage:text];
  2198. }
  2199. else {
  2200. [self setDefaultBottomViewStatus];
  2201. }
  2202. }
  2203. - (void)touristSendMessage:(NSString *)text {
  2204. TXLiveTextMessage *message = [[TXLiveTextMessage alloc] init];
  2205. message.userInfo = [self getCurrentUser];
  2206. message.text = text;
  2207. MJWeakSelf;
  2208. [self sendTextMessage:message priority:V2TIM_PRIORITY_NORMAL displayMessage:YES callback:^(BOOL success) {
  2209. [weakSelf setDefaultBottomViewStatus];
  2210. }];
  2211. }
  2212. - (TXLiveUser *)getCurrentUser {
  2213. TXLiveUser *user = [[TXLiveUser alloc] init];
  2214. user.sendUserId = UserDefault(IM_USERID);
  2215. user.sendUserName = UserDefault(NicknameKey);
  2216. user.avatarUrl = UserDefault(AvatarUrlKey);
  2217. return user;
  2218. }
  2219. /**
  2220. 点赞
  2221. */
  2222. - (void)praiseBtnPressed {
  2223. if (self.enableLike == NO) {
  2224. [self MBPShow:@"管理员已关闭点赞功能"];
  2225. return;
  2226. }
  2227. NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
  2228. __weak __typeof(&*self)weakSelf = self;
  2229. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.21 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  2230. if ([[NSDate date] timeIntervalSince1970] - self.lastClickPraiseTime >= 0.2) {
  2231. [weakSelf modifyLikeCount:clickPraiseBtnTimes];
  2232. clickPraiseBtnTimes = 0;
  2233. }
  2234. });
  2235. clickPraiseBtnTimes++;
  2236. self.lastClickPraiseTime = currentTime;
  2237. [self presentLikeMessageAnimation];
  2238. }
  2239. - (void)modifyLikeCount:(NSInteger)count {
  2240. [[V2TIMManager sharedInstance] increaseGroupCounter:self.roomId key:@"LIKES" value:count succ:^(NSDictionary<NSString *,NSNumber *> *groupCounters) {
  2241. } fail:^(int code, NSString *desc) {
  2242. }];
  2243. }
  2244. /**
  2245. 赞动画
  2246. */
  2247. - (void)presentLikeMessageAnimation {
  2248. LiveRoomLikeLayer *layer = [[LiveRoomLikeLayer alloc] initWithName:@"Like"];
  2249. [self.videoContainerView.layer addSublayer:layer];
  2250. CGRect tempFrame = [self.videoContainerView convertRect:self.bottomView.likeButton.frame fromView:self.bottomView];
  2251. CGFloat width = tempFrame.size.width;
  2252. CGFloat height = tempFrame.size.height;
  2253. CGFloat dx = CGRectGetMidX(tempFrame) - width *0.5;
  2254. CGFloat dy = CGRectGetMidY(tempFrame) - 8 - height;
  2255. layer.frame = CGRectMake(dx, dy, width, height);
  2256. [layer startAnimation];
  2257. }
  2258. - (void)displaySeatApplyView {
  2259. [self.applyView showInView:self.view];
  2260. }
  2261. - (void)displayApplyingView {
  2262. [self.applyingView showInView:self.view];
  2263. }
  2264. - (LiveApplyView *)applyView {
  2265. if (!_applyView) {
  2266. _applyView = [LiveApplyView shareInstance];
  2267. MJWeakSelf;
  2268. [_applyView applySeatCallback:^{
  2269. [weakSelf applySeatAction];
  2270. }];
  2271. }
  2272. return _applyView;
  2273. }
  2274. - (void)applySeatAction {
  2275. [self sendSeatMessageApply:YES];
  2276. }
  2277. - (void)sendSeatMessageApply:(BOOL)isApply {
  2278. if (self.micStatus == MICSTATUS_CONNECTING) {
  2279. [self MBPShow:@"您已上麦"];
  2280. return;
  2281. }
  2282. SEATHANDLE type = isApply ? SEATHANDLE_APPLY : SEATHANDLE_CANCELAPPLY;
  2283. TXLiveMessageSeatApply *applyMessage = [[TXLiveMessageSeatApply alloc] init];
  2284. applyMessage.type = type;
  2285. applyMessage.audienceId = UserDefault(IM_USERID);
  2286. applyMessage.audienceName = UserDefault(NicknameKey);
  2287. applyMessage.audienceAvatar = UserDefault(AvatarUrlKey);
  2288. applyMessage.teacherId = self.createrId;
  2289. applyMessage.teacherName = self.createrName;
  2290. applyMessage.userInfo = [self getCurrentUser];
  2291. MJWeakSelf;
  2292. [self sendCustomMessage:applyMessage priority:V2TIM_PRIORITY_HIGH displayMessage:YES callback:^(BOOL success) {
  2293. if (success) {
  2294. weakSelf.micStatus = isApply ? MICSTATUS_WAITING : MICSTATUS_NOMAL;
  2295. }
  2296. }];
  2297. }
  2298. - (LiveApplyingView *)applyingView {
  2299. if (!_applyingView) {
  2300. _applyingView = [LiveApplyingView shareInstance];
  2301. NSString *avatar = UserDefaultObjectForKey(AvatarUrlKey);
  2302. [_applyingView.myAvatal sd_setImageWithURL:[NSURL URLWithString:[avatar getUrlEndcodeString]] placeholderImage:[UIImage imageNamed:USERDEFAULT_LOGO]];
  2303. [_applyingView.teacherAvatal sd_setImageWithURL:[NSURL URLWithString:[self.createrAvatal getUrlEndcodeString]] placeholderImage:[UIImage imageNamed:USERDEFAULT_LOGO]];
  2304. MJWeakSelf;
  2305. [_applyingView cancleApplyCallback:^{
  2306. [weakSelf cancleApplyAction];
  2307. }];
  2308. }
  2309. return _applyingView;
  2310. }
  2311. - (void)cancleApplyAction {
  2312. MJWeakSelf;
  2313. self.alertView = [LiveAlertView shareInstance];
  2314. [self.alertView alertWithTitle:@"连麦申请中,确认取消连麦申请吗?" desc:@"断开后如想再次连麦可重新发起" leftButtonTitle:@"取消" rightTitle:@"确定关闭" inView:self.view cancel:^{
  2315. } confirm:^{
  2316. [weakSelf.applyingView hideView];
  2317. [weakSelf sendSeatMessageApply:NO];
  2318. }];
  2319. }
  2320. #pragma mark ---- sendMessage/showMessage
  2321. // 文本消息
  2322. - (void)sendTextMessage:(TXLiveMessageModel *)messageContent priority:(V2TIMMessagePriority)priority displayMessage:(BOOL)displayMessage callback:(void(^)(BOOL success))callback {
  2323. NSData *msgData = [messageContent encodeMessage];
  2324. if (msgData == nil) {
  2325. return;
  2326. }
  2327. __weak typeof(&*self) __weakself = self;
  2328. [TXLiveMessageCenter sendLiveChatMessage:msgData groupId:self.roomId priority:priority success:^{
  2329. dispatch_async(dispatch_get_main_queue(), ^{
  2330. if (displayMessage) {
  2331. [__weakself appendAndDisplayMessage:messageContent];
  2332. }
  2333. [__weakself.inputBar clearInputView];
  2334. callback(YES);
  2335. });
  2336. } failer:^(int code, NSString * _Nonnull msg) {
  2337. dispatch_async(dispatch_get_main_queue(), ^{
  2338. [__weakself.inputBar clearInputView];
  2339. NSLog(@"发送失败,errorcode is: %d message: %@",code, msg);
  2340. callback(NO);
  2341. });
  2342. }];
  2343. }
  2344. // 其他消息
  2345. - (void)sendCustomMessage:(TXLiveMessageModel *)messageContent priority:(V2TIMMessagePriority)priority displayMessage:(BOOL)displayMessage callback:(void(^)(BOOL success))callback {
  2346. NSData *msgData = [messageContent encodeMessage];
  2347. if (msgData == nil) {
  2348. return;
  2349. }
  2350. __weak typeof(&*self) __weakself = self;
  2351. [TXLiveMessageCenter sendLiveChatMessage:msgData groupId:self.roomId priority:priority success:^{
  2352. dispatch_async(dispatch_get_main_queue(), ^{
  2353. if (displayMessage) {
  2354. [__weakself appendAndDisplayMessage:messageContent];
  2355. }
  2356. callback(YES);
  2357. });
  2358. } failer:^(int code, NSString * _Nonnull msg) {
  2359. dispatch_async(dispatch_get_main_queue(), ^{
  2360. NSLog(@"发送失败,errorcode is: %d message: %@",code, msg);
  2361. callback(NO);
  2362. });
  2363. }];
  2364. }
  2365. /**
  2366. * 将消息加入本地数组
  2367. */
  2368. - (void)appendAndDisplayMessage:(TXLiveMessageModel *)liveMessage {
  2369. if (!liveMessage) {
  2370. return;
  2371. }
  2372. if ([self appendMessageModel:liveMessage]) {
  2373. NSIndexPath *indexPath =
  2374. [NSIndexPath indexPathForItem:self.conversationDataRepository.count - 1
  2375. inSection:0];
  2376. if ([self.conversationMessageTableView numberOfRowsInSection:0] !=
  2377. self.conversationDataRepository.count - 1) {
  2378. return;
  2379. }
  2380. // view刷新
  2381. [self.conversationMessageTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2382. if ([self isAtTheBottomOfTableView] || self.isNeedScrollToButtom) {
  2383. [self scrollToBottomAnimated:NO];
  2384. self.isNeedScrollToButtom=NO;
  2385. }
  2386. }
  2387. return;
  2388. }
  2389. /**
  2390. * 如果当前会话没有这个消息id,把消息加入本地数组
  2391. */
  2392. - (BOOL)appendMessageModel:(TXLiveMessageModel *)model {
  2393. if (!model) {
  2394. return NO;
  2395. }
  2396. //这里可以根据消息类型来决定是否显示,如果不希望显示直接return NO
  2397. //数量不可能无限制的大,这里限制收到消息过多时,就对显示消息数量进行限制。
  2398. //用户可以手动下拉更多消息,查看更多历史消息。
  2399. if (self.conversationDataRepository.count>500) {
  2400. [self.conversationDataRepository removeObjectAtIndex:0];
  2401. [self.conversationMessageTableView reloadData];
  2402. }
  2403. [self.conversationDataRepository addObject:model];
  2404. return YES;
  2405. }
  2406. - (void)showAnimationView:(BOOL)isJoinRoom showMessag:(NSString *)message {
  2407. if (self.landScape) {
  2408. return;
  2409. }
  2410. if (self.enterAnimationView && self.enterAnimationView.isShow) {
  2411. return;
  2412. }
  2413. else {
  2414. ANIMATIONTYPE type = isJoinRoom ? ANIMATIONTYPE_JOIN : ANIMATIONTYPE_RUSH;
  2415. self.enterAnimationView = [[LiveAnimationView alloc] initWithTitle:message animationType:type];
  2416. [self.view addSubview:self.enterAnimationView];
  2417. [self.enterAnimationView mas_makeConstraints:^(MASConstraintMaker *make) {
  2418. make.left.right.mas_equalTo(self.view);
  2419. make.width.mas_equalTo(KPortraitWidth);
  2420. make.height.mas_equalTo(24.0f);
  2421. make.bottom.mas_equalTo(self.messageContentView.mas_top).offset(-6);
  2422. }];
  2423. [self.view bringSubviewToFront:self.enterAnimationView];
  2424. MJWeakSelf;
  2425. [self.enterAnimationView startAnimationEndCallback:^{
  2426. weakSelf.enterAnimationView.isShow = NO;
  2427. weakSelf.enterAnimationView = nil;
  2428. }];
  2429. }
  2430. }
  2431. - (NSMutableArray *)remoteMemberArray {
  2432. if (!_remoteMemberArray) {
  2433. _remoteMemberArray = [NSMutableArray array];
  2434. }
  2435. return _remoteMemberArray;
  2436. }
  2437. - (TXLiveLoadingView *)loadingView {
  2438. if (!_loadingView) {
  2439. _loadingView = [TXLiveLoadingView shareInstance];
  2440. }
  2441. return _loadingView;
  2442. }
  2443. - (void)showLoading {
  2444. if (![self.videoView.subviews containsObject:self.loadingView]) {
  2445. [self.loadingView showLoadingView:self.videoView];
  2446. }
  2447. }
  2448. - (void)hideLoading {
  2449. if ([self.videoView.subviews containsObject:self.loadingView]) {
  2450. [self.loadingView hideLoadingView];
  2451. }
  2452. }
  2453. - (void)micButtonAction:(BOOL)isMute {
  2454. if (isMute == !self.micEnable) {
  2455. return;
  2456. }
  2457. if (_trtcCloud && self.isAudience == NO) {
  2458. self.micEnable = !isMute;
  2459. [self.trtcCloud muteLocalAudio:!self.micEnable];
  2460. [self syncMicStatus:!self.micEnable];
  2461. }
  2462. }
  2463. - (void)syncMicStatus:(BOOL)isMute {
  2464. TXMicStatusSync *syncMic = [[TXMicStatusSync alloc] init];
  2465. syncMic.userInfo = [self getCurrentUser];
  2466. syncMic.userId = UserDefault(IM_USERID);
  2467. syncMic.muteMic = isMute;
  2468. [self sendCustomMessage:syncMic priority:V2TIM_PRIORITY_HIGH displayMessage:NO callback:^(BOOL success) {
  2469. }];
  2470. [self renderSeatView];
  2471. }
  2472. #pragma mark ---- 3A config
  2473. - (void)setSubjectId:(NSString *)subjectId {
  2474. _subjectId = subjectId;
  2475. // 设置 3A参数
  2476. self.ANS = 0;
  2477. self.AEC = 100;
  2478. // 长号14和萨克斯5 AGC 一样
  2479. if ([subjectId isEqualToString:@"5"] || [subjectId isEqualToString:@"14"]) {
  2480. self.AGC = 45;
  2481. }
  2482. else if ([subjectId isEqualToString:@"16"]) { // 次中音号
  2483. self.AGC = 80;
  2484. }
  2485. else if ([subjectId isEqualToString:@"12"]) {
  2486. self.AGC = 50;
  2487. }
  2488. else {
  2489. self.AGC = 0;
  2490. }
  2491. }
  2492. /*
  2493. #pragma mark - Navigation
  2494. // In a storyboard-based application, you will often want to do a little preparation before navigation
  2495. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  2496. // Get the new view controller using [segue destinationViewController].
  2497. // Pass the selected object to the new view controller.
  2498. }
  2499. */
  2500. @end