NTESNetChatViewController.m 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  1. //
  2. // NTESNetChatViewController.m
  3. // NIM
  4. //
  5. // Created by chris on 15/5/18.
  6. // Copyright (c) 2015年 Netease. All rights reserved.
  7. //
  8. #import "NTESNetChatViewController.h"
  9. #import "UIAlertView+NTESBlock.h"
  10. #import "UIView+Toast.h"
  11. #import "NTESTimerHolder.h"
  12. #import "NTESNetCallChatInfo.h"
  13. #import "NTESBundleSetting.h"
  14. #import <AVFoundation/AVFoundation.h>
  15. #import <AssetsLibrary/ALAssetsLibrary.h>
  16. #import <Photos/Photos.h>
  17. #import "UIView+NTES.h"
  18. //十秒之后如果还是没有收到对方响应的control字段,则自己发起一个假的control,用来激活铃声并自己先进入房间
  19. #define DelaySelfStartControlTime 10
  20. //激活铃声后无人接听的超时时间
  21. #define NoBodyResponseTimeOut 45
  22. //周期性检查剩余磁盘空间
  23. #define DiskCheckTimeInterval 10
  24. //剩余磁盘空间不足的警告阈值
  25. #define MB (1024ll * 1024ll)
  26. #define FreeDiskSpaceWarningThreshold (10 * MB)
  27. @interface NTESNetChatViewController ()
  28. @property(nonatomic, strong) NTESTimerHolder *timer;
  29. @property(nonatomic, strong) NSMutableArray *chatRoom;
  30. @property(nonatomic, assign) BOOL recordWillStopForLackSpace;
  31. @property(nonatomic, strong) NTESTimerHolder *diskCheckTimer;
  32. @property(nonatomic, assign) BOOL userHangup;
  33. @property(nonatomic, strong) NTESTimerHolder *calleeResponseTimer; //被叫等待用户响应接听或者拒绝的时间
  34. @property(nonatomic, assign) BOOL calleeResponsed;
  35. @property(nonatomic, assign) int successRecords;
  36. //@property (nonatomic, strong) NTESRecordSelectView * recordView;
  37. @end
  38. @implementation NTESNetChatViewController {
  39. UInt64 CallId;
  40. }
  41. - (BOOL)forbidInteractivePop {
  42. return YES;
  43. }
  44. - (instancetype)initWithCallee:(NSString *)callee {
  45. self = [self initWithNibName:nil bundle:nil];
  46. if (self) {
  47. self.peerUid = callee;
  48. self.callInfo.callee = callee;
  49. self.callInfo.caller = [[NIMSDK sharedSDK].loginManager currentAccount];
  50. }
  51. return self;
  52. }
  53. - (instancetype)initWithCaller:(NSString *)caller callId:(uint64_t)callID {
  54. self = [self initWithNibName:nil bundle:nil];
  55. if (self) {
  56. self.peerUid = caller;
  57. self.callInfo.caller = caller;
  58. self.callInfo.callee = [[NIMSDK sharedSDK].loginManager currentAccount];
  59. self.callInfo.callID = callID;
  60. }
  61. return self;
  62. }
  63. - (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
  64. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  65. if (self) {
  66. self.edgesForExtendedLayout = UIRectEdgeAll;
  67. if (!self.callInfo) {
  68. [[NIMSDK sharedSDK].mediaManager switchAudioOutputDevice:NIMAudioOutputDeviceSpeaker];
  69. _callInfo = [[NTESNetCallChatInfo alloc] init];
  70. }
  71. _timer = [[NTESTimerHolder alloc] init];
  72. _diskCheckTimer = [[NTESTimerHolder alloc] init];
  73. //防止应用在后台状态,此时呼入,会走init但是不会走viewDidLoad,此时呼叫方挂断,导致被叫监听不到,界面无法消去的问题。
  74. id <NIMNetCallManager> manager = [NIMAVChatSDK sharedSDK].netCallManager;
  75. [manager addDelegate:self];
  76. }
  77. return self;
  78. }
  79. - (void)dealloc {
  80. NSLog(@"vc dealloc info : %@", self);
  81. [[NIMAVChatSDK sharedSDK].netCallManager removeDelegate:self];
  82. }
  83. - (void)viewDidLoad {
  84. [super viewDidLoad];
  85. __weak typeof(self) wself = self;
  86. [[NIMAVChatSDK sharedSDK].netCallManager addDelegate:self];
  87. [self checkServiceEnable:^(BOOL result) {
  88. if (result) {
  89. // [self response:YES];
  90. [wself afterCheckService];
  91. } else {
  92. //用户禁用服务,干掉界面
  93. if (wself.callInfo.callID) {
  94. //说明是被叫方
  95. [[NIMAVChatSDK sharedSDK].netCallManager response:wself.callInfo.callID accept:NO option:nil completion:nil];
  96. }
  97. [wself dismiss:nil];
  98. }
  99. }];
  100. }
  101. - (void)viewWillAppear:(BOOL)animated {
  102. [super viewWillAppear:animated];
  103. }
  104. - (void)viewDidAppear:(BOOL)animated {
  105. [super viewDidAppear:animated];
  106. [UIApplication sharedApplication].idleTimerDisabled = YES;
  107. }
  108. - (void)viewWillDisappear:(BOOL)animated {
  109. [super viewWillDisappear:animated];
  110. [self.player stop];
  111. // [[NIMAVChatSDK sharedSDK].netCallManager hangup:CallId];
  112. [UIApplication sharedApplication].idleTimerDisabled = NO;
  113. }
  114. - (void)afterCheckService {
  115. if (self.callInfo.isStart) {
  116. [self.timer startTimer:0.5 delegate:self repeats:YES];
  117. [self onCalling];
  118. } else if (self.callInfo.callID) {
  119. [self startByCallee];
  120. } else {
  121. [self startByCaller];
  122. }
  123. [self checkFreeDiskSpace];
  124. [self.diskCheckTimer startTimer:DiskCheckTimeInterval
  125. delegate:self
  126. repeats:YES];
  127. }
  128. #pragma mark - Subclass Impl
  129. - (void)startByCaller {
  130. if (self.callInfo.callType == NIMNetCallTypeVideo) {
  131. //视频呼叫马上发起
  132. [self doStartByCaller];
  133. } else {
  134. //语音呼叫先播放一断提示音,然后再发起
  135. [self playConnnetRing];
  136. __weak typeof(self) wself = self;
  137. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  138. if (!wself) {
  139. return;
  140. }
  141. if (wself.userHangup) {
  142. NSLog(@"Netcall request was cancelled before, ignore it.");
  143. return;
  144. }
  145. [wself doStartByCaller];
  146. });
  147. }
  148. }
  149. - (void)doStartByCaller {
  150. self.callInfo.isStart = YES;
  151. NSArray *callees = [NSArray arrayWithObjects:self.callInfo.callee, nil];
  152. NIMNetCallOption *option = [[NIMNetCallOption alloc] init];
  153. option.extendMessage = @"音视频请求扩展信息";
  154. option.apnsContent = [NSString stringWithFormat:@"%@请求", self.callInfo.callType == NIMNetCallTypeAudio ? @"网络通话" : @"视频聊天"];
  155. // option.apnsInuse = NO;
  156. option.apnsSound = @"video_chat_push.mp3";
  157. [self fillUserSetting:option];
  158. option.videoCaptureParam.startWithCameraOn = (self.callInfo.callType == NIMNetCallTypeVideo);
  159. __weak typeof(self) wself = self;
  160. [[NIMAVChatSDK sharedSDK].netCallManager start:callees type:wself.callInfo.callType option:option completion:^(NSError *error, UInt64 callID) {
  161. if (!error && wself) {
  162. NSLog(@"呼叫成功");
  163. CallId = callID;
  164. wself.callInfo.callID = callID;
  165. wself.chatRoom = [[NSMutableArray alloc] init];
  166. //十秒之后如果还是没有收到对方响应的control字段,则自己发起一个假的control,用来激活铃声并自己先进入房间
  167. NSTimeInterval delayTime = DelaySelfStartControlTime;
  168. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  169. [wself onControl:callID from:wself.callInfo.callee type:NIMNetCallControlTypeFeedabck];
  170. });
  171. } else {
  172. NSLog(@"呼叫失败");
  173. if (error) {
  174. NSLog(@"连接失败跳转%@", error);
  175. [wself.navigationController.view makeToast:@"连接失败"
  176. duration:2
  177. position:CSToastPositionCenter];
  178. } else {
  179. //说明在start的过程中把页面关了。。
  180. [[NIMAVChatSDK sharedSDK].netCallManager hangup:callID];
  181. }
  182. [wself dismiss:nil];
  183. }
  184. }];
  185. }
  186. - (void)startByCallee {
  187. //告诉对方可以播放铃声了
  188. self.callInfo.isStart = YES;
  189. NSMutableArray *room = [[NSMutableArray alloc] init];
  190. [room addObject:self.callInfo.caller];
  191. self.chatRoom = room;
  192. [[NIMAVChatSDK sharedSDK].netCallManager control:self.callInfo.callID type:NIMNetCallControlTypeFeedabck];
  193. [self playReceiverRing];
  194. _calleeResponseTimer = [[NTESTimerHolder alloc] init];
  195. [_calleeResponseTimer startTimer:NoBodyResponseTimeOut delegate:self repeats:NO];
  196. }
  197. - (void)hangup {
  198. _userHangup = YES;
  199. [[NIMAVChatSDK sharedSDK].netCallManager hangup:self.callInfo.callID];
  200. if (self.callInfo.localRecording) {
  201. __weak typeof(self) wself = self;
  202. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  203. wself.chatRoom = nil;
  204. [wself dismiss:nil];
  205. });
  206. } else {
  207. self.chatRoom = nil;
  208. [self dismiss:nil];
  209. }
  210. }
  211. - (void)response:(BOOL)accept {
  212. _calleeResponsed = YES;
  213. NIMNetCallOption *option = [[NIMNetCallOption alloc] init];
  214. [self fillUserSetting:option];
  215. __weak typeof(self) wself = self;
  216. [[NIMAVChatSDK sharedSDK].netCallManager response:self.callInfo.callID accept:accept option:option completion:^(NSError *error, UInt64 callID) {
  217. if (!error) {
  218. NSLog(@"被接成功");
  219. [wself onCalling];
  220. [wself.player stop];
  221. [wself.chatRoom addObject:wself.callInfo.callee];
  222. NSTimeInterval delay = 10.f; //10秒后判断下房间
  223. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  224. if (wself.chatRoom.count == 1) {
  225. [wself.navigationController.view makeToast:@"通话失败"
  226. duration:2
  227. position:CSToastPositionCenter];
  228. [wself hangup];
  229. }
  230. });
  231. } else {
  232. NSLog(@"被接失败");
  233. wself.chatRoom = nil;
  234. [wself.navigationController.view makeToast:@"连接失败"
  235. duration:2
  236. position:CSToastPositionCenter];
  237. [wself dismiss:nil];
  238. }
  239. }];
  240. //dismiss需要放在self后面,否在ios7下会有野指针
  241. if (accept) {
  242. [self waitForConnectiong];
  243. } else {
  244. [self dismiss:nil];
  245. }
  246. }
  247. //- (void)onReceive:(UInt64)callID from:(NSString *)caller type:(NIMNetCallMediaType)type message:(NSString *)extendMessage{
  248. //
  249. //// NTESMainTabController *tabVC = [NTESMainTabController instance];
  250. //// [tabVC.view endEditing:YES];
  251. //// UINavigationController *nav = tabVC.selectedViewController;
  252. ////
  253. //// if ([self shouldResponseBusy]){
  254. //// [[NIMAVChatSDK sharedSDK].netCallManager control:callID type:NIMNetCallControlTypeBusyLine];
  255. //// }
  256. //// else {
  257. ////
  258. //// if ([self shouldFireNotification:caller]) {
  259. //// NSString *text = [self textByCaller:caller
  260. //// type:type];
  261. //// [_notifier start:text];
  262. //// }
  263. //
  264. //
  265. //
  266. // UIViewController *vc;
  267. // switch (type) {
  268. // case NIMNetCallTypeVideo:{
  269. // vc = [[NTESNetChatViewController alloc] initWithCaller:caller callId:callID];
  270. //// [self response:NO];
  271. // }
  272. // break;
  273. // case NIMNetCallTypeAudio:{
  274. //// vc = [[NTESAudioChatViewController alloc] initWithCaller:caller callId:callID];
  275. // }
  276. // break;
  277. // default:
  278. // break;
  279. // }
  280. // if (!vc) {
  281. // return;
  282. // }
  283. //
  284. // // 由于音视频聊天里头有音频和视频聊天界面的切换,直接用present的话页面过渡会不太自然,这里还是用push,然后做出present的效果
  285. //// CATransition *transition = [CATransition animation];
  286. //// transition.duration = 0.25;
  287. //// transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
  288. //// transition.type = kCATransitionPush;
  289. //// transition.subtype = kCATransitionFromTop;
  290. //// [nav.view.layer addAnimation:transition forKey:nil];
  291. //// nav.navigationBarHidden = YES;
  292. //// if (nav.presentedViewController) {
  293. //// // fix bug MMC-1431
  294. //// [nav.presentedViewController dismissViewControllerAnimated:NO completion:nil];
  295. //// }
  296. //// [nav pushViewController:vc animated:NO];
  297. //// }
  298. //}
  299. - (void)dismiss:(void (^)(void))completion {
  300. [self dismissViewControllerAnimated:YES completion:^{
  301. if (completion) {
  302. completion();
  303. }
  304. }];
  305. }
  306. - (void)onCalling {
  307. //子类重写
  308. }
  309. - (void)waitForConnectiong {
  310. //子类重写
  311. }
  312. - (void)onCalleeBusy {
  313. //子类重写
  314. }
  315. - (BOOL)startAudioRecording {
  316. UInt64 timestamp = [[NSDate date] timeIntervalSince1970] * 1000;
  317. NSString *pathComponent = [NSString stringWithFormat:@"record_audio%@_%llu", [[NIMSDK sharedSDK].loginManager currentAccount], timestamp];
  318. NSURL *filePath = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:pathComponent];
  319. return [[NIMAVChatSDK sharedSDK].netCallManager startAudioRecording:filePath error:nil];
  320. }
  321. - (BOOL)startLocalRecording {
  322. UInt64 timestamp = [[NSDate date] timeIntervalSince1970] * 1000;
  323. NSString *pathComponent = [NSString stringWithFormat:@"record_%@_%llu.mp4", [[NIMSDK sharedSDK].loginManager currentAccount], timestamp];
  324. NSURL *filePath = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:pathComponent];
  325. BOOL startAccepted;
  326. startAccepted = [[NIMAVChatSDK sharedSDK].netCallManager startRecording:filePath
  327. videoBitrate:(UInt32) [[NTESBundleSetting sharedConfig] localRecordVideoKbps] * 1000
  328. uid:[[NIMSDK sharedSDK].loginManager currentAccount]
  329. ];
  330. return startAccepted;
  331. }
  332. - (BOOL)startOtherSideRecording {
  333. UInt64 timestamp = [[NSDate date] timeIntervalSince1970] * 1000;
  334. NSString *pathComponent = [NSString stringWithFormat:@"record_%@_%llu.mp4", self.peerUid, timestamp];
  335. NSURL *filePath = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:pathComponent];
  336. BOOL startAccepted;
  337. startAccepted = [[NIMAVChatSDK sharedSDK].netCallManager startRecording:filePath
  338. videoBitrate:(UInt32) [[NTESBundleSetting sharedConfig] localRecordVideoKbps] * 1000
  339. uid:self.peerUid
  340. ];
  341. return startAccepted;
  342. }
  343. - (void)stopAudioRecording {
  344. [[NIMAVChatSDK sharedSDK].netCallManager stopAudioRecording];
  345. self.callInfo.audioConversation = NO;
  346. }
  347. - (BOOL)stopLocalRecording {
  348. return [[NIMAVChatSDK sharedSDK].netCallManager stopRecordingWithUid:[[NIMSDK sharedSDK].loginManager currentAccount]];
  349. }
  350. - (BOOL)stopOtherSideRecording {
  351. return [[NIMAVChatSDK sharedSDK].netCallManager stopRecordingWithUid:self.peerUid];
  352. }
  353. - (void)udpateLowSpaceWarning:(BOOL)show {
  354. //子类重写
  355. }
  356. - (void)recordWithAudioConversation:(BOOL)audioConversationOn myMedia:(BOOL)myMediaOn otherSideMedia:(BOOL)otherSideMediaOn video:(BOOL)isVideo {
  357. NSString *toastText = @"";
  358. int records = 0;
  359. _successRecords = 0;//不包括语音对话
  360. //语音对话
  361. if (audioConversationOn) {
  362. records++;
  363. if (!self.callInfo.audioConversation) {
  364. toastText = @"语音对话开始失败";
  365. }
  366. }
  367. //自己音视频
  368. if (myMediaOn) {
  369. records++;
  370. if (![self startLocalRecording]) {
  371. if (isVideo) {
  372. toastText = [toastText stringByAppendingString:[toastText isEqualToString:@""] ? @"自己音视频开始失败" : @",自己音视频开始失败"];
  373. } else {
  374. toastText = [toastText stringByAppendingString:[toastText isEqualToString:@""] ? @"自己音频开始失败" : @",自己音频开始失败"];
  375. }
  376. } else
  377. _successRecords++;
  378. }
  379. //对方音视频
  380. if (otherSideMediaOn) {
  381. records++;
  382. if (![self startOtherSideRecording]) {
  383. if (isVideo) {
  384. toastText = [toastText stringByAppendingString:[toastText isEqualToString:@""] ? @"对方音视频开始失败" : @",对方音视频开始失败"];
  385. } else {
  386. toastText = [toastText stringByAppendingString:[toastText isEqualToString:@""] ? @"对方音频开始失败" : @",对方音频开始失败"];
  387. }
  388. } else
  389. _successRecords++;
  390. }
  391. //判断是否需要提示
  392. if (![toastText isEqualToString:@""]) {
  393. if ([toastText componentsSeparatedByString:@","].count == records) {
  394. [self.view makeToast:@"开始录制失败"
  395. duration:2
  396. position:CSToastPositionCenter];
  397. } else {
  398. [self.view makeToast:toastText
  399. duration:2
  400. position:CSToastPositionCenter];
  401. }
  402. }
  403. }
  404. - (void)stopRecordTaskWithVideo:(BOOL)isVideo {
  405. NSString *toastText = @"";
  406. int records = 0;
  407. //结束自己音视频
  408. if (self.callInfo.localRecording) {
  409. records++;
  410. if (![self stopLocalRecording]) {
  411. if (isVideo) {
  412. toastText = [toastText stringByAppendingString:[toastText isEqualToString:@""] ? @"自己音视频结束失败" : @",自己音视频结束失败"];
  413. } else {
  414. toastText = [toastText stringByAppendingString:[toastText isEqualToString:@""] ? @"自己音频结束失败" : @",自己音频结束失败"];
  415. }
  416. }
  417. }
  418. //结束对方音视频
  419. if (self.callInfo.otherSideRecording) {
  420. records++;
  421. if (![self stopOtherSideRecording]) {
  422. if (isVideo) {
  423. toastText = [toastText stringByAppendingString:[toastText isEqualToString:@""] ? @"对方音视频结束失败" : @",对方音视频结束失败"];
  424. } else {
  425. toastText = [toastText stringByAppendingString:[toastText isEqualToString:@""] ? @"对方音频结束失败" : @",对方音频结束失败"];
  426. }
  427. }
  428. }
  429. //判断是否要提示
  430. if (![toastText isEqualToString:@""]) {
  431. if ([toastText componentsSeparatedByString:@","].count == records) {
  432. [self.view makeToast:@"结束录制失败"
  433. duration:3
  434. position:CSToastPositionCenter];
  435. } else {
  436. [self.view makeToast:toastText
  437. duration:3
  438. position:CSToastPositionCenter];
  439. }
  440. }
  441. }
  442. - (BOOL)allRecordsStopped {
  443. //当前没有录制任务
  444. if (!self.callInfo.localRecording && !self.callInfo.otherSideRecording && !self.callInfo.audioConversation) {
  445. return YES;
  446. } else {
  447. return NO;
  448. }
  449. }
  450. - (BOOL)allRecordsSucceeed {
  451. int num = self.callInfo.localRecording + self.callInfo.otherSideRecording;
  452. if (num == _successRecords) {
  453. return YES;
  454. } else {
  455. return NO;
  456. }
  457. }
  458. - (NSString *)peerUid {
  459. if (_peerUid) {
  460. return _peerUid;
  461. } else {
  462. if ([_callInfo.callee isEqualToString:[[NIMSDK sharedSDK].loginManager currentAccount]]) {
  463. _peerUid = _callInfo.caller;
  464. return _callInfo.caller;
  465. } else {
  466. _peerUid = _callInfo.callee;
  467. return _callInfo.callee;
  468. }
  469. }
  470. }
  471. //-(void)showRecordSelectView:(BOOL)isVideo
  472. //{
  473. // if (!_recordView) {
  474. // _recordView = [[NTESRecordSelectView alloc]initWithFrame:CGRectMake(0, 0, 250, 250) Video:isVideo];
  475. // _recordView.delegate = self;
  476. // _recordView.centerX = self.view.width/2;
  477. // _recordView.centerY = self.view.height/2;
  478. // }
  479. // [self.view addSubview:_recordView];
  480. //}
  481. #pragma mark - NIMNetCallManagerDelegate
  482. - (void)onControl:(UInt64)callID
  483. from:(NSString *)user
  484. type:(NIMNetCallControlType)control {
  485. if (user == [[NIMSDK sharedSDK].loginManager currentAccount]) {
  486. //多端登录时,自己会收到自己发出的控制指令,这里忽略他
  487. return;
  488. }
  489. if (callID != self.callInfo.callID) {
  490. return;
  491. }
  492. switch (control) {
  493. case NIMNetCallControlTypeFeedabck: {
  494. NSMutableArray *room = self.chatRoom;
  495. if (room && !room.count && !_userHangup) {
  496. [self playSenderRing];
  497. [room addObject:self.callInfo.caller];
  498. //40秒之后查看一下房间状态,如果房间还在一个人的话,就播放铃声超时
  499. __weak typeof(self) wself = self;
  500. uint64_t callId = self.callInfo.callID;
  501. NSTimeInterval delayTime = NoBodyResponseTimeOut;
  502. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  503. NSMutableArray *room = wself.chatRoom;
  504. if (wself && room && room.count == 1) {
  505. [[NIMAVChatSDK sharedSDK].netCallManager hangup:callId];
  506. wself.chatRoom = nil;
  507. [wself playTimeoutRing];
  508. [wself.navigationController.view makeToast:@"无人接听"
  509. duration:2
  510. position:CSToastPositionCenter];
  511. [wself startChat];
  512. [wself dismiss:nil];
  513. }
  514. });
  515. }
  516. break;
  517. }
  518. case NIMNetCallControlTypeBusyLine: {
  519. [self onCalleeBusy];
  520. [self playOnCallRing];
  521. _userHangup = YES;
  522. [[NIMAVChatSDK sharedSDK].netCallManager hangup:callID];
  523. __weak typeof(self) wself = self;
  524. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (3.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  525. [wself startChat];
  526. [wself dismiss:nil];
  527. });
  528. break;
  529. }
  530. case NIMNetCallControlTypeStartRecord:
  531. [self.view makeToast:@"对方开始了录制"
  532. duration:1
  533. position:CSToastPositionCenter];
  534. break;
  535. case NIMNetCallControlTypeStopRecord:
  536. [self.view makeToast:@"对方结束了录制"
  537. duration:1
  538. position:CSToastPositionCenter];
  539. break;
  540. default:
  541. break;
  542. }
  543. }
  544. - (void)onResponse:(UInt64)callID from:(NSString *)callee accepted:(BOOL)accepted {
  545. if (self.callInfo.callID == callID) {
  546. if (!accepted) {
  547. self.chatRoom = nil;
  548. [self.navigationController.view makeToast:@"对方拒绝接听"
  549. duration:2
  550. position:CSToastPositionCenter];
  551. [self playHangUpRing];
  552. __weak typeof(self) wself = self;
  553. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (3.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  554. [wself startChat];
  555. [wself dismiss:nil];
  556. });
  557. } else {
  558. [self.player stop];
  559. [self onCalling];
  560. [self.chatRoom addObject:callee];
  561. }
  562. }
  563. }
  564. - (void)onCallEstablished:(UInt64)callID {
  565. if (self.callInfo.callID == callID) {
  566. self.callInfo.startTime = [NSDate date].timeIntervalSince1970;
  567. [self.timer startTimer:0.5 delegate:self repeats:YES];
  568. }
  569. }
  570. - (void)onCallDisconnected:(UInt64)callID withError:(NSError *)error {
  571. if (self.callInfo.callID == callID) {
  572. [self.timer stopTimer];
  573. [self dismiss:nil];
  574. self.chatRoom = nil;
  575. }
  576. }
  577. - (void)onResponsedByOther:(UInt64)callID
  578. accepted:(BOOL)accepted {
  579. [self.view.window makeToast:@"已在其他端处理"
  580. duration:2
  581. position:CSToastPositionCenter];
  582. [self dismiss:nil];
  583. }
  584. - (void)onHangup:(UInt64)callID
  585. by:(NSString *)user {
  586. if (self.callInfo.callID == callID) {
  587. [self.player stop];
  588. if (self.callInfo.localRecording) {
  589. __weak typeof(self) wself = self;
  590. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  591. [wself dismiss:nil];
  592. });
  593. } else {
  594. [self dismiss:nil];
  595. }
  596. }
  597. }
  598. - (void)onRecordStarted:(UInt64)callID fileURL:(NSURL *)fileURL uid:(NSString *)userId {
  599. if (self.callInfo.callID == callID) {
  600. if ([userId isEqualToString:[[NIMSDK sharedSDK].loginManager currentAccount]]) {
  601. self.callInfo.localRecording = YES;
  602. }
  603. if ([userId isEqualToString:self.peerUid]) {
  604. self.callInfo.otherSideRecording = YES;
  605. }
  606. }
  607. }
  608. - (void)onRecordError:(NSError *)error
  609. callID:(UInt64)callID
  610. uid:(NSString *)userId {
  611. NSLog(@"Local record error %@ (%zd)", error.localizedDescription, error.code);
  612. if (self.callInfo.callID == callID) {
  613. [self.view makeToast:[NSString stringWithFormat:@"录制发生错误: %zd", error.code]
  614. duration:2
  615. position:CSToastPositionCenter];
  616. if ([userId isEqualToString:[[NIMSDK sharedSDK].loginManager currentAccount]]) {
  617. self.callInfo.localRecording = NO;
  618. }
  619. if ([userId isEqualToString:self.peerUid]) {
  620. self.callInfo.otherSideRecording = NO;
  621. }
  622. }
  623. if (error.code == NIMAVLocalErrorCodeRecordWillStopForLackSpace) {
  624. _recordWillStopForLackSpace = YES;
  625. }
  626. }
  627. - (void)onRecordStopped:(UInt64)callID
  628. fileURL:(NSURL *)fileURL
  629. uid:(NSString *)userId {
  630. if (self.callInfo.callID == callID) {
  631. if ([userId isEqualToString:[[NIMSDK sharedSDK].loginManager currentAccount]]) {
  632. self.callInfo.localRecording = NO;
  633. }
  634. if ([userId isEqualToString:self.peerUid]) {
  635. self.callInfo.otherSideRecording = NO;
  636. }
  637. //辅助验证: 写到系统相册
  638. [self requestAuthorizationSaveToPhotosAlbum:fileURL];
  639. }
  640. }
  641. #pragma mark - NTESRecordSelectViewDelegate
  642. - (void)onRecordWithAudioConversation:(BOOL)audioConversationOn myMedia:(BOOL)myMediaOn otherSideMedia:(BOOL)otherSideMediaOn {
  643. //子类重写
  644. }
  645. #pragma mark - M80TimerHolderDelegate
  646. - (void)onNTESTimerFired:(NTESTimerHolder *)holder {
  647. if (holder == self.diskCheckTimer) {
  648. [self checkFreeDiskSpace];
  649. } else if (holder == self.calleeResponseTimer) {
  650. if (!_calleeResponsed) {
  651. [self.navigationController.view makeToast:@"接听超时"
  652. duration:2
  653. position:CSToastPositionCenter];
  654. [self response:NO];
  655. }
  656. }
  657. }
  658. #pragma mark - Misc
  659. - (void)checkServiceEnable:(void (^)(BOOL))result {
  660. if ([[AVAudioSession sharedInstance] respondsToSelector:@selector(requestRecordPermission:)]) {
  661. [[AVAudioSession sharedInstance] performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
  662. dispatch_async_main_safe(^{
  663. if (granted) {
  664. NSString *mediaType = AVMediaTypeVideo;
  665. AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
  666. if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
  667. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
  668. message:@"相机权限受限,无法视频聊天"
  669. delegate:nil
  670. cancelButtonTitle:@"确定"
  671. otherButtonTitles:nil];
  672. [alert showAlertWithCompletionHandler:^(NSInteger idx) {
  673. if (result) {
  674. result(NO);
  675. }
  676. }];
  677. } else {
  678. if (result) {
  679. result(YES);
  680. }
  681. }
  682. } else {
  683. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
  684. message:@"麦克风权限受限,无法聊天"
  685. delegate:nil
  686. cancelButtonTitle:@"确定"
  687. otherButtonTitles:nil];
  688. [alert showAlertWithCompletionHandler:^(NSInteger idx) {
  689. if (result) {
  690. result(NO);
  691. }
  692. }];
  693. }
  694. });
  695. }];
  696. }
  697. }
  698. - (UIStatusBarStyle)preferredStatusBarStyle {
  699. return UIStatusBarStyleLightContent;
  700. }
  701. - (void)requestAuthorizationSaveToPhotosAlbum:(NSURL *)fileURL {
  702. __weak typeof(self) wself = self;
  703. if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
  704. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
  705. if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
  706. //没有权限
  707. dispatch_async_main_safe(^{
  708. [wself.navigationController.view makeToast:@"保存失败,没有相册权限"
  709. duration:3
  710. position:CSToastPositionCenter];
  711. });
  712. } else if (status == PHAuthorizationStatusAuthorized) {
  713. //有权限
  714. [wself saveToPhotosAlbum:fileURL];
  715. }
  716. }];
  717. } else {
  718. [self saveToPhotosAlbum:fileURL];
  719. }
  720. }
  721. - (void)saveToPhotosAlbum:(NSURL *)fileURL {
  722. if (fileURL) {
  723. __weak typeof(self) wself = self;
  724. if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
  725. ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
  726. [library writeVideoAtPathToSavedPhotosAlbum:fileURL
  727. completionBlock:^(NSURL *assetURL, NSError *error) {
  728. [wself checkVideoSaveToAlbum:error];
  729. }];
  730. } else {
  731. [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
  732. [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:fileURL];
  733. }
  734. completionHandler:^(BOOL success, NSError *_Nullable error) {
  735. dispatch_async_main_safe(^{
  736. [wself checkVideoSaveToAlbum:error];
  737. });
  738. }];
  739. }
  740. }
  741. }
  742. - (void)checkVideoSaveToAlbum:(NSError *)error {
  743. NSString *toast = _recordWillStopForLackSpace ? @"你的手机内存不足,录制已结束\n" : @"录制已结束\n";
  744. if (error) {
  745. toast = [NSString stringWithFormat:@"%@保存至系统相册失败:%zd", toast, error.code];
  746. } else {
  747. toast = [toast stringByAppendingString:@"录制文件已保存至系统相册"];
  748. }
  749. if (!self.callInfo.localRecording && !self.callInfo.otherSideRecording && _successRecords == 1) {
  750. [self.navigationController.view makeToast:toast
  751. duration:3
  752. position:CSToastPositionCenter];
  753. }
  754. _successRecords--;
  755. }
  756. - (void)checkFreeDiskSpace {
  757. if (self.callInfo.localRecording) {
  758. uint64_t freeSpace = 1000 * MB;
  759. NSError *error;
  760. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  761. NSDictionary *attrbites = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error:&error];
  762. if (attrbites) {
  763. NSNumber *freeFileSystemSizeInBytes = [attrbites objectForKey:NSFileSystemFreeSize];
  764. freeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];
  765. [self udpateLowSpaceWarning:(freeSpace < FreeDiskSpaceWarningThreshold)];
  766. }
  767. }
  768. }
  769. - (void)fillUserSetting:(NIMNetCallOption *)option {
  770. option.autoRotateRemoteVideo = [[NTESBundleSetting sharedConfig] videochatAutoRotateRemoteVideo];
  771. option.serverRecordAudio = [[NTESBundleSetting sharedConfig] serverRecordAudio];
  772. option.serverRecordVideo = [[NTESBundleSetting sharedConfig] serverRecordVideo];
  773. option.preferredVideoEncoder = [[NTESBundleSetting sharedConfig] perferredVideoEncoder];
  774. option.preferredVideoDecoder = [[NTESBundleSetting sharedConfig] perferredVideoDecoder];
  775. option.videoMaxEncodeBitrate = [[NTESBundleSetting sharedConfig] videoMaxEncodeKbps] * 1000;
  776. option.autoDeactivateAudioSession = [[NTESBundleSetting sharedConfig] autoDeactivateAudioSession];
  777. option.audioDenoise = [[NTESBundleSetting sharedConfig] audioDenoise];
  778. option.voiceDetect = [[NTESBundleSetting sharedConfig] voiceDetect];
  779. option.audioHowlingSuppress = [[NTESBundleSetting sharedConfig] audioHowlingSuppress];
  780. option.preferHDAudio = [[NTESBundleSetting sharedConfig] preferHDAudio];
  781. option.scene = [[NTESBundleSetting sharedConfig] scene];
  782. NIMNetCallVideoCaptureParam *param = [[NIMNetCallVideoCaptureParam alloc] init];
  783. [self fillVideoCaptureSetting:param];
  784. option.videoCaptureParam = param;
  785. }
  786. - (void)fillVideoCaptureSetting:(NIMNetCallVideoCaptureParam *)param {
  787. param.preferredVideoQuality = [[NTESBundleSetting sharedConfig] preferredVideoQuality];
  788. param.videoCrop = [[NTESBundleSetting sharedConfig] videochatVideoCrop];
  789. param.startWithBackCamera = [[NTESBundleSetting sharedConfig] startWithBackCamera];
  790. }
  791. #pragma mark - Ring
  792. //铃声 - 正在呼叫请稍后
  793. - (void)playConnnetRing {
  794. [self.player stop];
  795. NSURL *url = [[NSBundle mainBundle] URLForResource:@"video_connect_chat_tip_sender" withExtension:@"aac"];
  796. self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
  797. [self.player play];
  798. }
  799. //铃声 - 对方暂时无法接听
  800. - (void)playHangUpRing {
  801. [self.player stop];
  802. NSURL *url = [[NSBundle mainBundle] URLForResource:@"video_chat_tip_HangUp" withExtension:@"aac"];
  803. self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
  804. [self.player play];
  805. }
  806. //铃声 - 对方正在通话中
  807. - (void)playOnCallRing {
  808. [self.player stop];
  809. NSURL *url = [[NSBundle mainBundle] URLForResource:@"video_chat_tip_OnCall" withExtension:@"aac"];
  810. self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
  811. [self.player play];
  812. }
  813. //铃声 - 对方无人接听
  814. - (void)playTimeoutRing {
  815. [self.player stop];
  816. NSURL *url = [[NSBundle mainBundle] URLForResource:@"video_chat_tip_onTimer" withExtension:@"aac"];
  817. self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
  818. [self.player play];
  819. }
  820. //铃声 - 接收方铃声
  821. - (void)playReceiverRing {
  822. [self.player stop];
  823. NSURL *url = [[NSBundle mainBundle] URLForResource:@"video_chat_tip_receiver" withExtension:@"aac"];
  824. self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
  825. self.player.numberOfLoops = 20;
  826. [self.player play];
  827. }
  828. //铃声 - 拨打方铃声
  829. - (void)playSenderRing {
  830. [self.player stop];
  831. NSURL *url = [[NSBundle mainBundle] URLForResource:@"video_chat_tip_sender" withExtension:@"aac"];
  832. self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
  833. self.player.numberOfLoops = 20;
  834. [self.player play];
  835. }
  836. - (void)startChat {
  837. NSString *now = [Helper getCurrentTimes];
  838. NSString *str = [NSString stringWithFormat:@"%@order?action=doBegVChat&pk=%@&modelpk=%@&begdate=%@&hasanswer=0", imageURl, [Helper sharedAccount].accid, self.modelPk, now];
  839. NSLog(@"str========%@", str);
  840. [[AHHttpManager sharedManager] POST:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:nil success:^(id responseObject) {
  841. NSLog(@"%@", responseObject);
  842. if ([[responseObject objectForKey:@"msg"] isEqualToString:@"success"]) {
  843. } else {
  844. //[MBProgressHUD showTextHUD:@"超时" inView:self.view hideAfterDelay:1];
  845. }
  846. } failure:^(NSError *error) {
  847. NSLog(@"error = %@", error);
  848. //[MBProgressHUD showTextHUD:@"超时" inView:self.view hideAfterDelay:1];
  849. }];
  850. }
  851. @end