// // LCOnIntercomViewController.m // LCOnDemo // // Created by 陈嘉乐 on 2021/4/26. // #import "LCOnIntercomViewController.h" #import #import #import #import "LCUtlis.h" #import "LCApiKit.h" #import @interface LCOnIntercomViewController () @property (nonatomic,assign) BOOL playing; @property (nonatomic,assign) BOOL isInterrupt; @property (nonatomic,assign) BOOL isSpeaking; @property (nonatomic,strong) UIImage *snapImage; //截图 @property (nonatomic, strong) UIButton *backButton; // @property (nonatomic, strong) UILabel *titleUILabel; // @property (nonatomic, strong) UIView *centerView; //内容背景View @property (nonatomic, strong) UIView *videoView; @property (nonatomic, strong) UIView *unlockView; @property (nonatomic, strong) UIButton *screenshotImgBtn; //截图 @property (nonatomic, strong) UIButton *unlockImgBtn; //开锁 @property (nonatomic, strong) UIButton *hangUpImgBtn;//挂断按钮 @property (nonatomic, strong) UIButton *hangUpTextBtn; @property (nonatomic, strong) UIButton *answerImgBtn;//接听按钮 @property (nonatomic, strong) UIButton *answerTextBtn; @property (nonatomic, strong) UIButton *calltimeBtn; //通话时间按钮 //定时器 @property (nonatomic,strong) dispatch_source_t countdownTimer; @property (nonatomic,strong) dispatch_source_t openDoorTimer; @property (nonatomic, assign) int openDoorTimeout; @property (nonatomic, assign) int callTimeout; /// 播放器 @property (nonatomic, strong) LCOpenSDK_PlayWindow *playWindow; ///对讲 @property (strong, nonatomic) LCOpenSDK_AudioTalk *talker; @end @implementation LCOnIntercomViewController{ BOOL isAccessAudio; BOOL isAccessVideo; BOOL isBackGround; BOOL iSVideoNotDetermined; BOOL iSAudioNotDetermined; BOOL isAnswer;//是否已经点击接听过了 NSString * tipStr; NSString * okStr; NSString * saveToTheAlbumsStr; NSString * operationFailedStr; NSString * refuseStr; NSString * answerStr; NSString * unlockSuccessfullyStr; NSString * callingStr; NSString * hangUpStr; NSString * endOfCallStr; // int openDoorTimeout; //全局变量 SystemSoundID sound; CGFloat Height66; bool isShowErrorAlert; } - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = UIColor.whiteColor; Height66 = GetRealWidth(66); [self initLlanguage]; [self initTopBarView]; [self initCentetView]; [self initData]; // [self setAnswerBtnEnable:NO]; [self initESVideo]; //开始反呼 [self StartReverseCall]; [self ShowCalltimeBtn:callingStr]; // //暂时不支持开锁功能 // [self setUnlock:NO]; //注册开锁成功监听 [self addOpenSuccessAction]; // Do any additional setup after loading the view. } -(void)initLlanguage{ NSString *languageName = [[[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"] objectAtIndex:0]; // 简体中文 if ([languageName rangeOfString:@"zh-Hans"].location != NSNotFound) { tipStr = @"提示"; okStr = @"确认"; saveToTheAlbumsStr = @"已保存至手机相册."; operationFailedStr = @"操作失败"; refuseStr = @"拒绝"; answerStr = @"接听"; hangUpStr = @"挂断"; unlockSuccessfullyStr = @"开锁成功"; callingStr = @"来电中..."; endOfCallStr = @"通话结束"; }else{ tipStr = @"Prompt"; okStr = @"OK"; saveToTheAlbumsStr = @"Saved to the albums."; operationFailedStr = @"Operation failed."; refuseStr = @"Refuse"; answerStr = @"Answer"; hangUpStr = @"Hang up"; unlockSuccessfullyStr = @"Unlock successfully"; callingStr = @"Incoming call"; endOfCallStr = @"End of call"; } } - (void)initTopBarView { UIView *TopView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, APP_TOP_BAR_HEIGHT)]; TopView.backgroundColor = HEXCOLORA(0xF7F7F7,1.0); // [TopView addSubview:self.backButton]; [TopView addSubview:self.titleUILabel]; [self.view addSubview:TopView]; TopView.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.25].CGColor; TopView.layer.shadowOffset = CGSizeMake(0,0.5); TopView.layer.shadowOpacity = 1; TopView.layer.shadowRadius = 0; } - (UIButton *)backButton{ if (_backButton == nil) { _backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, APP_STATUS_BAR_HEIGHT, 44, 44)]; [_backButton setImage:[UIImage imageNamed:@"ic_esvideo_on_back"] forState:UIControlStateNormal]; _backButton.imageEdgeInsets = UIEdgeInsetsMake(12,12,12,12); [_backButton.imageView setContentMode:UIViewContentModeScaleAspectFit]; [_backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside]; } return _backButton; } -(void)backAction{ [self.navigationController popViewControllerAnimated:true]; // [self dismissViewControllerAnimated:YES completion:NULL]; } -(UILabel *)titleUILabel{ if (_titleUILabel == Nil) { _titleUILabel = [[UILabel alloc] initWithFrame:CGRectMake(90, APP_STATUS_BAR_HEIGHT, self.view.frame.size.width - 180, 44)]; _titleUILabel.font = [UIFont fontWithName:APP_UIFont_BOLD size:18.0]; _titleUILabel.textColor = TextColor; _titleUILabel.text = @""; _titleUILabel.textAlignment = NSTextAlignmentCenter; } return _titleUILabel; } - (void)initCentetView { [self.view addSubview:self.centerView]; // [self.centerView addSubview:self.collectButton]; [self.centerView addSubview:self.videoView]; [self.centerView addSubview:self.unlockView]; [self.unlockView addSubview:self.screenshotImgBtn]; [self.unlockView addSubview:self.unlockImgBtn]; [self.centerView addSubview:self.hangUpImgBtn]; [self.centerView addSubview:self.hangUpTextBtn]; [self.centerView addSubview:self.answerImgBtn]; [self.centerView addSubview:self.answerTextBtn]; [self.centerView addSubview:self.calltimeBtn]; } - (UIView *)centerView{ if (_centerView == nil) { _centerView = [[UIButton alloc] initWithFrame:CGRectMake(0, APP_TOP_BAR_HEIGHT, APP_SCREEN_WIDTH, APP_VISIBLE_HEIGHT)]; _centerView.backgroundColor = UIColor.whiteColor; } return _centerView; } -(void)setRadiusWithView:(UIView *)mView{ //顶部圆角 UIRectCorner corners = UIRectCornerTopLeft | UIRectCornerTopRight; if (@available(iOS 11.0, *)) { mView.layer.cornerRadius = 20; mView.layer.maskedCorners = (CACornerMask)corners; }else{ UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:mView.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(20,20)]; //创建 layer CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init]; maskLayer.frame = mView.bounds; //赋值 maskLayer.path = maskPath.CGPath; mView.layer.mask = maskLayer; } } -(UIView *)videoView{ if (_videoView == Nil) { _videoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, GetRealWidth(210))]; _videoView.backgroundColor = UIColor.lightGrayColor; _videoView.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.25].CGColor; _videoView.layer.shadowOffset = CGSizeMake(0,0.5); _videoView.layer.shadowOpacity = 1; _videoView.layer.shadowRadius = 0; } return _videoView; } - (UIView *)unlockView{ if (_unlockView == nil) { _unlockView = [[UIView alloc] initWithFrame:CGRectMake(0, GetRealWidth(210), APP_SCREEN_WIDTH, GetRealWidth(72))]; _unlockView.backgroundColor = HEXCOLORA(0x232323, 1.0); _unlockView.layer.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0].CGColor; _unlockView.layer.shadowColor = [UIColor colorWithRed:204/255.0 green:204/255.0 blue:204/255.0 alpha:0.4].CGColor; _unlockView.layer.shadowOffset = CGSizeMake(0,0.5); _unlockView.layer.shadowOpacity = 1; _unlockView.layer.shadowRadius = 0; } return _unlockView; } - (UIButton *)screenshotImgBtn{ if (_screenshotImgBtn == nil) { _screenshotImgBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, GetRealWidth(44), GetRealWidth(44))]; [_screenshotImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_takephoto_unselect"] forState:UIControlStateNormal]; // [_screenshotImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_takephoto_select"] forState:UIControlStateSelected]; [_screenshotImgBtn.imageView setContentMode:UIViewContentModeScaleAspectFit]; [_screenshotImgBtn addTarget:self action:@selector(screenshotAction) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside]; [_screenshotImgBtn addTarget:self action:@selector(screenshotDownAction) forControlEvents:UIControlEventTouchDown]; _screenshotImgBtn.adjustsImageWhenHighlighted = NO; _screenshotImgBtn.center = CGPointMake(APP_SCREEN_WIDTH/4, GetRealWidth(38)); } return _screenshotImgBtn; } -(void)screenshotDownAction{ [_screenshotImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_takephoto_select"] forState:UIControlStateNormal]; } -(void)screenshotAction{ [_screenshotImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_takephoto_unselect"] forState:UIControlStateNormal]; // //截图 //截图 if(self.playWindow){ [self saveThumbImage]; } } - (UIButton *)unlockImgBtn{ if (_unlockImgBtn == nil) { _unlockImgBtn = [[UIButton alloc] initWithFrame:CGRectMake(0,0, GetRealWidth(44), GetRealWidth(44))]; [_unlockImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_unlock_unselect"] forState:UIControlStateNormal]; // [_unlockImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_unlock_select"] forState:UIControlStateSelected]; [_unlockImgBtn.imageView setContentMode:UIViewContentModeScaleAspectFit]; [_unlockImgBtn addTarget:self action:@selector(unlockAction) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside]; [_unlockImgBtn addTarget:self action:@selector(unlockDownAction) forControlEvents:UIControlEventTouchDown]; _unlockImgBtn.adjustsImageWhenHighlighted = NO; _unlockImgBtn.center = CGPointMake((APP_SCREEN_WIDTH/4) * 3, GetRealWidth(38)); } return _unlockImgBtn; } -(void)unlockDownAction{ [_unlockImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_unlock_select"] forState:UIControlStateNormal]; } -(void)unlockAction{ [_unlockImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_unlock_unselect"] forState:UIControlStateNormal]; //开锁 if(self.mLCCallDelegate != NULL){ [self.mLCCallDelegate onUnlockAction]; } } #pragma 挂断和开锁 - (UIButton *)hangUpImgBtn{ if (_hangUpImgBtn == nil) { _hangUpImgBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, Height66, Height66)]; [_hangUpImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_hangup"] forState:UIControlStateNormal]; // [_hangUpImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_hangup"] forState:UIControlStateSelected]; [_hangUpImgBtn.imageView setContentMode:UIViewContentModeScaleAspectFit]; [_hangUpImgBtn addTarget:self action:@selector(hangUpAction) forControlEvents:UIControlEventTouchUpInside]; _hangUpImgBtn.center = CGPointMake(APP_SCREEN_WIDTH/4, GetRealHeight(452) + Height66/2); } return _hangUpImgBtn; } //挂断按钮事件 -(void)hangUpAction{ //1.回调事件 if(self.mLCCallDelegate != NULL){ if(isAnswer){ //如果之前已经接听了,回调是挂断 [self.mLCCallDelegate onHangUpAction:_callTimeout]; }else{ //如果之前没接听了,回调是拒接 [self.mLCCallDelegate onRejectCallAction]; } } //2.页面关闭 [self backAction]; } - (UIButton *)hangUpTextBtn{ if (_hangUpTextBtn == nil) { _hangUpTextBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, GetRealWidth(100), GetRealWidth(20))]; [_hangUpTextBtn setTitle:@"拒绝" forState:UIControlStateNormal]; _hangUpTextBtn.titleLabel.textAlignment = NSTextAlignmentCenter; _hangUpTextBtn.titleLabel.font = [UIFont fontWithName:APP_UIFont size:14.0]; [_hangUpTextBtn setTitleColor:TextColor forState:UIControlStateNormal]; [_hangUpTextBtn setTitleColor:TextSelectColor forState:UIControlStateSelected]; [_hangUpTextBtn addTarget:self action:@selector(screenshotAction) forControlEvents:UIControlEventTouchUpInside]; _hangUpTextBtn.center = CGPointMake(_hangUpImgBtn.center.x, GetRealHeight(530)); } return _hangUpTextBtn; } - (UIButton *)answerImgBtn{ if (_answerImgBtn == nil) { _answerImgBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, Height66, Height66)]; [_answerImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_answer"] forState:UIControlStateNormal]; // [_answerImgBtn setImage:[UIImage imageNamed:@"ic_esvideo_on_answer"] forState:UIControlStateSelected]; [_answerImgBtn.imageView setContentMode:UIViewContentModeScaleAspectFit]; [_answerImgBtn addTarget:self action:@selector(answerIAction) forControlEvents:UIControlEventTouchUpInside]; _answerImgBtn.center = CGPointMake((APP_SCREEN_WIDTH/4)*3, GetRealHeight(452) + Height66/2); } return _answerImgBtn; } -(void)answerIAction{ [self stopPlaySystemSound]; /// 开启对讲 [self startTalk]; _answerImgBtn.hidden = YES; _answerTextBtn.hidden = YES; //挂断按钮移动中间 _hangUpImgBtn.center = CGPointMake(APP_CONTENT_WIDTH/2, _hangUpImgBtn.center.y); _hangUpTextBtn.center = CGPointMake(APP_CONTENT_WIDTH/2, _hangUpTextBtn.center.y); [_hangUpTextBtn setTitle:hangUpStr forState:UIControlStateNormal]; //开始计时 _callTimeout = 0; [self startCountdown]; isAnswer = YES; if(self.mLCCallDelegate != NULL){ [self.mLCCallDelegate onAnswerAction]; } } -(void)setAnswerBtnEnable:(BOOL)ISEnable{ [_answerImgBtn setEnabled:ISEnable]; [_answerTextBtn setEnabled:ISEnable]; } - (UIButton *)answerTextBtn{ if (_answerTextBtn == nil) { _answerTextBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, GetRealWidth(100), GetRealWidth(20))]; [_answerTextBtn setTitle:@"接听" forState:UIControlStateNormal]; _answerTextBtn.titleLabel.font = [UIFont fontWithName:APP_UIFont size:14.0]; _answerTextBtn.titleLabel.textAlignment = NSTextAlignmentCenter; // _unlockTextBtn.titleLabel.textColor = TextColor; [_answerTextBtn setTitleColor:TextColor forState:UIControlStateNormal]; [_answerTextBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled]; [_answerTextBtn setTitleColor:TextSelectColor forState:UIControlStateSelected]; [_answerTextBtn addTarget:self action:@selector(unlockAction) forControlEvents:UIControlEventTouchUpInside]; _answerTextBtn.center = CGPointMake(_answerImgBtn.center.x, GetRealHeight(530)); } return _answerTextBtn; } - (UIButton *)calltimeBtn{ if (_calltimeBtn == nil) { _calltimeBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, GetRealWidth(100), GetRealWidth(40))]; _calltimeBtn.backgroundColor = HEXCOLORA(0x000000, 0.6); [_calltimeBtn setTitle:@"00:00" forState:UIControlStateNormal]; _calltimeBtn.titleLabel.font = [UIFont fontWithName:APP_UIFont size:14.0]; _calltimeBtn.titleLabel.textAlignment = NSTextAlignmentCenter; [_calltimeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; _calltimeBtn.hidden = YES; _calltimeBtn.layer.cornerRadius = 12; _calltimeBtn.center = CGPointMake(APP_CONTENT_WIDTH/2, GetRealWidth(340)); } return _calltimeBtn; } -(void)ShowTime:(int)nowTime { if(_calltimeBtn.hidden) _calltimeBtn.hidden = NO; NSString *timeStr = [self timeFormatted:nowTime]; [self setCalltimeButtonText:timeStr isTime:YES]; } -(void)ShowCalltimeBtn:(NSString*) mesStr { if(_calltimeBtn.hidden) _calltimeBtn.hidden = NO; [self setCalltimeButtonText:mesStr isTime:NO]; } /* 根据文字调整按钮宽 */ -(void)setCalltimeButtonText:(NSString*) mesStr isTime:(BOOL)isTime { [_calltimeBtn setTitle:mesStr forState:UIControlStateNormal]; if(isTime){ _calltimeBtn.frame = CGRectMake(0, 0, GetRealWidth(80), GetRealWidth(30)); }else{ _calltimeBtn.frame = CGRectMake(0, 0, GetRealWidth(115), GetRealWidth(30)); } _calltimeBtn.center = CGPointMake(APP_SCREEN_WIDTH/2, GetRealWidth(340)); } - (NSString *)timeFormatted:(int)totalSeconds { int seconds = totalSeconds % 60; int minutes = (totalSeconds / 60); return [NSString stringWithFormat:@"%02d:%02d", minutes, seconds]; } - (int *)getTextWidth:(UIButton*) btn { int textWidth = 0; //   CGSize size = [btn.titleLabel.textsizeWithFont:[UIFontboldSystemFontOfSize:15]constrainedToSize:contentMaxSizes lineBreakMode:UILineBreakModeCharacterWrap]; // textWidth = (int)fontSize.Width; return textWidth; } /** 开启倒计时 */ - (void)startCountdown { if (_callTimeout > 100) { return; } _callTimeout = 0; // GCD定时器 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); _countdownTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); dispatch_source_set_timer(_countdownTimer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0); //每秒执行 dispatch_source_set_event_handler(_countdownTimer, ^{ WEAKSELF_AT if(weakSelf_AT.callTimeout >= 100 ){// 计时结束 // 关闭定时器 dispatch_source_cancel(weakSelf_AT.countdownTimer); dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"超时"); [weakSelf_AT backAction]; }); }else{// 计时中 weakSelf_AT.callTimeout++; dispatch_async(dispatch_get_main_queue(), ^{ [weakSelf_AT ShowTime:weakSelf_AT.callTimeout]; }); } }); // 开启定时器 dispatch_resume(_countdownTimer); } #pragma 开锁成功 -(void)setOpenDoorSuccess{ [self setUnlock:NO]; _openDoorTimeout = 0; [self startOpenDoorCountdown]; [self showUIAlertView:unlockSuccessfullyStr]; } -(void)setUnlock:(BOOL)ISEnable{ [_unlockImgBtn setEnabled:ISEnable]; } /** 开启倒计时 */ - (void)startOpenDoorCountdown { if (_openDoorTimeout > 20) { return; } _openDoorTimeout = 0; // GCD定时器 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); _openDoorTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); dispatch_source_set_timer(_openDoorTimer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0); //每秒执行 dispatch_source_set_event_handler(_openDoorTimer, ^{ WEAKSELF_AT if(weakSelf_AT.openDoorTimeout >= 20 ){// 计时结束 // 关闭定时器 dispatch_source_cancel(weakSelf_AT.openDoorTimer); dispatch_async(dispatch_get_main_queue(), ^{ [weakSelf_AT setUnlock:YES]; }); }else{// 计时中 weakSelf_AT.openDoorTimeout++; } }); // 开启定时器 dispatch_resume(_openDoorTimer); } #pragma SDK可视对讲 功能部分 -(void)initESVideo{ // _es = ESVideo.shareInstance.es; //初始化中断,进入后台的tag [self.centerView addSubview:[self.playWindow getWindowView]]; _playing = NO; _isSpeaking = NO; self.isInterrupt = NO; isBackGround = NO; } -(void)initData{ _titleUILabel.text = [[LCApiKit sharedInstance] currentDeviceName]; [_hangUpTextBtn setTitle:refuseStr forState:UIControlStateNormal]; [_answerTextBtn setTitle:answerStr forState:UIControlStateNormal]; } ///播放窗口懒加载 - (LCOpenSDK_PlayWindow *)playWindow { if (!_playWindow) { /** 1. 初始化播放窗口信息,包括位置大小以及索引 */ _playWindow = [[LCOpenSDK_PlayWindow alloc] initPlayWindow:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, GetRealWidth(210)) Index:0]; /** 2. 设置播放窗口背景色 */ [_playWindow setSurfaceBGColor:[UIColor blackColor]]; /** 3. 添加播放窗口到父视图 */ // [self.view addSubview:[m_play getWindowView]]; /** 4. 设置监听对象,可监听播放结果回调 */ [_playWindow setWindowListener:(id)self]; } return _playWindow; } - (LCOpenSDK_AudioTalk *)talker { if (!_talker) { _talker = [LCOpenSDK_AudioTalk new]; [_talker setListener:self]; } return _talker; } //- (void)onResignActive{ // if (self.playWindow) { // [self.playWindow stopRtspReal:YES]; // // self.videoManager.isPlay = NO; // [self.playWindow stopAudio]; // } //} /** 暂停播放 */ - (void)stopPlay { if(self.playWindow){ [self.playWindow stopRtspReal:NO]; [self.playWindow stopAudio]; } if(self.talker){ [self.talker stopTalk]; } } - (void)startPlay { if(self.playWindow == NULL) return; [self.playWindow stopRtspReal:NO]; [self.playWindow stopAudio]; /** 1. 初始化实时预览播放参数对象 */ LCOpenSDK_ParamReal *paramReal = [[LCOpenSDK_ParamReal alloc] init]; /** 2. 设置token,token根据AppId和AppSecret调用乐橙云开放平台获取 */ paramReal.accessToken = [[LCApiKit sharedInstance] lcSdkToken]; /** 3. 设置设备序列号 */ paramReal.deviceID = [[LCApiKit sharedInstance] currentDeviceId]; /** 4. 设置设备通道,对于单通道设备为0, 对于NVR等多通道设备为具体通道号 */ paramReal.channel = 0; /** 5. 设置码流模式,支持主码流和子码流 */ paramReal.defiMode = DEFINITION_MODE_HG; /** 6. 设置密钥,如果为用户自定义密钥为具体密钥, 非用户自定密钥可为设备序列号*/ paramReal.psk = [[LCApiKit sharedInstance] currentPsk]; /** 7. 设置播放密钥,非必传,传了会提升拉流速度 */ paramReal.playToken = [[LCApiKit sharedInstance] currentDevicePlayToken];; /** 8. 是否走拉流优化,YES会提升拉流速度,建议传YES即可 */ paramReal.isOpt = YES; /** 8. 开始播放 */ [_playWindow playRtspReal:paramReal]; } /// 开启对讲 - (void)startTalk { if (!isAnswer) { //对讲开启 // [self.playWindow stopAudio]; if(self.talker == NULL) return; [self.talker stopTalk]; LCOpenSDK_ParamTalk *param = [[LCOpenSDK_ParamTalk alloc]init]; param.isOpt = YES; param.accessToken = [[LCApiKit sharedInstance] lcSdkToken]; /** 3. 设置设备序列号 */ param.deviceID = [[LCApiKit sharedInstance] currentDeviceId]; /** 4. 设置设备通道,对于单通道设备为0, 对于NVR等多通道设备为具体通道号 */ param.channel = 0; /** 6. 设置密钥,如果为用户自定义密钥为具体密钥, 非用户自定密钥可为设备序列号*/ param.psk = [[LCApiKit sharedInstance] currentPsk]; /** 7. 设置播放密钥,非必传,传了会提升拉流速度 */ param.playToken = [[LCApiKit sharedInstance] currentDevicePlayToken];; NSInteger result = [self.talker playTalk:param]; if (result != 0) { //错误处理 } } } /** 开始反呼 */ -(void)StartReverseCall{ [self startPlaySystemSound]; [self startPlay]; } #pragma ***************************SDKListener*************************** /** * 视频播放状态回调 * * @param code 错误码(根据type而定) * @param type 0, RTSP * 1, HLS * 99, OPENAPI * @param index 播放窗口索引值 */ /** 1. 播放结果回调,可根据错误码进行不同处理 */ - (void)onPlayerResult:(NSString*)code Type:(NSInteger)type Index:(NSInteger)index { // play WEAKSELF_AT(self); NSLog(@"LIVE_PLAY-CODE:%@,TYPE:%ld", code, type); //是否已经弹窗过 if(isShowErrorAlert) return;; dispatch_async(dispatch_get_main_queue(), ^{ if (99 == type) { if ([code isEqualToString:@"-1000"]) { //"网络请求失败 (%ld)" [weakSelf_AT showUIAlertViewWithBack:[NSString stringWithFormat:@"%@(%@)",self->endOfCallStr, code]]; } else if (![code isEqualToString:@"0"]) { //"网络请求失败 (%ld)" [weakSelf_AT showUIAlertViewWithBack:[NSString stringWithFormat:@"%@(%@)",self->endOfCallStr, code]]; } else { //成功 } } if (type == 5) { if ([code integerValue] != 0 && [code integerValue] != STATE_DHHTTP_OK) { [weakSelf_AT showUIAlertViewWithBack:[NSString stringWithFormat:@"%@(%@)",self->endOfCallStr, code]]; } } if (type == 0) { if ([RTSP_Result_String(STATE_RTSP_DESCRIBE_READY) isEqualToString:code]) { // dispatch_async(dispatch_get_main_queue(), ^{ // }); return; } if ([RTSP_Result_String(STATE_RTSP_PLAY_READY) isEqualToString:code]) { // dispatch_async(dispatch_get_main_queue(), ^{ // }); return; } //提示失败 [weakSelf_AT showUIAlertViewWithBack:[NSString stringWithFormat:@"%@(%@)",self->endOfCallStr, code]]; } }); return; } /** 2. 播放开始回调 */ - (void)onPlayBegan:(NSInteger)index { dispatch_async(dispatch_get_main_queue(), ^{ // self.videoManager.playStatus = 1001; // [self saveThumbImage]; // [self hideVideoLoadImage]; }); } /** * 语音对讲状态回调 * * @param error 错误码 * @param type 0, RTSP * 99, OPENAPI */ - (void)onTalkResult:(NSString *)error TYPE:(NSInteger)type { dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"开启对讲回调error = %@, type = %ld", error, (long)type); WEAKSELF_AT(self); // [LCProgressHUD hideAllHuds:nil]; // if (99 == type) { //网络请求失败 //// dispatch_async(dispatch_get_main_queue(), ^{ //// weakself.videoManager.isOpenAudioTalk = NO; //// [LCProgressHUD showMsg:@"play_module_video_preview_talk_failed".lc_T]; //// }); // return; // } // if (nil != error && [RTSP_Result_String(STATE_RTSP_DESCRIBE_READY) isEqualToString:error]) { // dispatch_async(dispatch_get_main_queue(), ^{ // }); // return; // } // if (nil != error && [RTSP_Result_String(STATE_RTSP_PLAY_READY) isEqualToString:error]) { // dispatch_async(dispatch_get_main_queue(), ^{ // //对讲连接成功建立 // self.videoManager.isOpenAudioTalk = YES; // [LCProgressHUD showMsg:@"device_mid_open_talk_success".lc_T]; // }); // return; // } // dispatch_async(dispatch_get_main_queue(), ^{ // [LCProgressHUD showMsg:@"play_module_video_preview_talk_failed".lc_T]; // weakself.videoManager.isOpenAudioTalk = NO; // }); }); } ////接听 //-(void)onAccept{ // if(_es){ // [_es onAccept]; // }else{ // NSLog(@"ES初始化失败"); // } // //} -(NSString *)getCurrentdateInterval { NSDate *datenow = [NSDate date]; NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)]; return timeSp; } -(void)showUIAlertView:(NSString *)mes { UIAlertController *alertController = [UIAlertController alertControllerWithTitle:tipStr message:mes preferredStyle:UIAlertControllerStyleAlert]; [alertController addAction:[UIAlertAction actionWithTitle:okStr style:UIAlertActionStyleCancel handler:nil]]; [self presentViewController:alertController animated:YES completion:nil]; // UIAlertView *alertView1 = [[UIAlertView alloc] initWithTitle:tipStr message:mes delegate:self cancelButtonTitle:okStr otherButtonTitles:nil, nil]; // [alertView1 show]; } /// -(void)showUIAlertViewWithBack:(NSString *)mes { isShowErrorAlert = true; UIAlertController *alertController = [UIAlertController alertControllerWithTitle:tipStr message:mes preferredStyle:UIAlertControllerStyleAlert]; [alertController addAction:[UIAlertAction actionWithTitle:okStr style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { [self backAction]; }]]; [self presentViewController:alertController animated:YES completion:nil]; } ///应用程会挂起 会调用 applicationWillResignActive 方法 - (void)onResignActive:(id)sender { [self stopPlay]; } #pragma viewDidAppear -(void)viewDidAppear:(BOOL)animated{ //这个方法请根据App的具体情况调用 } -(void)setIsInterrupt:(BOOL)isInterrupt{ // if (_es) { // _es.isInterrupt = isInterrupt; // } } -(void)viewWillDisappear:(BOOL)animated{ [super viewWillDisappear:animated]; [self stopPlaySystemSound]; //防止用户不按挂断,或者不等收到对方的挂断,点击返回按钮。 [self stopPlay]; // if(_es){ // [_es onHangup]; // [_es onStopCapture]; // [_es stopTalk]; // // _es.delegate = nil; // ESVideo.shareInstance.snapImageCallback = nil; // // // } // [_es freeSubClass]; } -(void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self]; // [_es freeSubClass]; if(_openDoorTimer){ dispatch_source_cancel(_openDoorTimer); _openDoorTimer = nil; // OK } if(_countdownTimer){ dispatch_source_cancel(_countdownTimer); _countdownTimer = nil; // OK } NSLog(@"==============dealloc"); } //#pragma mark ESVideoPhoneDelegate ////视频通话的状态代理事件,phoneEvent为返回的消息里面包含event状态与与event相关的数据 //-(void)getPhoneEvent_UI:(NSString *)phoneEvent{ // NSLog(@"事件%@", phoneEvent); // NSArray *strArray = [phoneEvent componentsSeparatedByString:@"\r\n"]; // NSArray *eventArray = [strArray.firstObject componentsSeparatedByString:@"="]; // NSString *phoneEventStr = eventArray.lastObject; // // if([phoneEventStr isEqual:@"EVT_Ringing"]){ // // _es.showView.hidden = NO; // //反呼成功 允许接听 看需求是否需要播放铃声和震动 // [self setAnswerBtnEnable:YES]; // // // [_mCallOrAccept setTitle:@"接听" forState:UIControlStateNormal]; // }else if([phoneEventStr isEqual:@"EVT_StartStream"]){ // // } else if([phoneEventStr isEqual:@"EVT_StopStream"]){ // // [_mCallOrAccept setTitle:@"反呼" forState:UIControlStateNormal]; // }else if([phoneEventStr isEqual:@"EVT_Connected"]){ // // // [_mCallOrAccept setTitle:@"通话中..." forState:UIControlStateNormal]; // }else if([phoneEventStr isEqual:@"EVT_HangUp"]){ // [self showUIAlertViewWithBack:@"已挂断"]; // // [_mCallOrAccept setTitle:@"反呼" forState:UIControlStateNormal]; // }else if([phoneEventStr isEqual:@"EVT_P2POnlineStatusChanged"]){ // //EVT_P2PStarted(p2p初始化OK,可以连接),EVT_P2POnlineStatusChangedonline=1 // //p2p初始化成功,手机端目前没有这个回调了 // //_mCallOrAccept.enabled = YES; // //_monitorBtn.enabled = YES; // }else if([phoneEventStr isEqual:@"EVT_RECV_CUSTOM_DATA"]){ // //开门的结果从这里返回 // NSString *baseStr = [strArray[1] substringFromIndex:5]; // NSData *data = [[NSData alloc]initWithBase64EncodedString:baseStr options:NSDataBase64DecodingIgnoreUnknownCharacters]; // NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; // NSInteger status = [[dic valueForKey:@"status"]integerValue]; // if(status && status == 1){ // NSLog(@"开门成功"); // [self setOpenDoorSuccess]; // }else{ // NSLog(@"开门失败"); // } // } //} #pragma mark AudioSession与Notifications处理 -(void)InterruptionEndedAVAudioSessionSetActiveYES{ if (isBackGround) { return; } if (self.isInterrupt == YES) { [self startPlay]; self.isInterrupt = NO; } } - (void)speaker:(UIButton *)sender { // [_es stopTalk]; // // NSString *result = nil; // //听筒状态 插耳塞后拔掉后恢复到默认设置 // if (sender == nil) { //// result = [_sessionHelper speaker:NO]; // [_es resetAudioCaptureIsSpeak:NO]; // }else{ // if(!_isSpeaking){ // [_es resetAudioCaptureIsSpeak:YES]; //// result = [_sessionHelper speaker:YES]; // _isSpeaking = YES; // }else{ //// result = [_sessionHelper speaker:NO]; // [_es resetAudioCaptureIsSpeak:NO]; // _isSpeaking = NO; // } // } // if (result) { // [sender setTitle:result forState:UIControlStateNormal]; // [_es startTalk]; // } } /* 需要注意的是,有一个中断开始消息不一定会有一个中断结束消息,这就意味着中断结束的回调里的处理逻辑可能会没有被执行到。 所以需要关注当切到前台运行状态时,是不是需要重新激活你的 Audio Session。 */ - (void)willEnterForeground:(NSNotification*)notification{ NSLog(@"willEnterForeground"); //初次启动会走这个通知(根页面),这时候是没有进入后台的 if (isBackGround) { return; } [self InterruptionEndedAVAudioSessionSetActiveYES]; } /// - (void)willEnterBackground:(NSNotification *)notification { isBackGround = YES; } #pragma 保存图片到相册 - (void)saveImageToPhotosAlbum:(UIImage *)savedImage { PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus]; if (status == PHAuthorizationStatusNotDetermined) { [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) { if(status == PHAuthorizationStatusAuthorized) { UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), NULL); } }]; } else { if (status == PHAuthorizationStatusAuthorized) { UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), NULL); } } } // 指定回调方法 - (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo { NSString *message = nil; if (!error) { message = saveToTheAlbumsStr; // 截图成功回调 if(self.mLCCallDelegate != NULL){ [self.mLCCallDelegate onScreenshotSuccessfulAction:image]; } } else { message = operationFailedStr; } [self showUIAlertView:message]; } /// 保存视频截图 - (void)saveThumbImage { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); NSString *libraryDirectory = [paths objectAtIndex:0]; NSString *myDirectory = [libraryDirectory stringByAppendingPathComponent:@"ON+"]; NSString *picDirectory = [myDirectory stringByAppendingPathComponent:@"picture"]; NSDateFormatter *dataFormat = [[NSDateFormatter alloc] init]; [dataFormat setDateFormat:@"yyyyMMddHHmmss"]; NSString *strDate = [dataFormat stringFromDate:[NSDate date]]; NSString *datePath = [picDirectory stringByAppendingPathComponent:strDate]; NSString *picPath = [datePath stringByAppendingString:@".jpg"]; NSLog(@"test jpg name[%@]\n", picPath); NSFileManager *fileManage = [NSFileManager defaultManager]; NSError *pErr; BOOL isDir; if (NO == [fileManage fileExistsAtPath:myDirectory isDirectory:&isDir]) { [fileManage createDirectoryAtPath:myDirectory withIntermediateDirectories:YES attributes:nil error:&pErr]; } if (NO == [fileManage fileExistsAtPath:picDirectory isDirectory:&isDir]) { [fileManage createDirectoryAtPath:picDirectory withIntermediateDirectories:YES attributes:nil error:&pErr]; } [self.playWindow snapShot:picPath]; UIImage *image = [UIImage imageWithContentsOfFile:picPath]; [self saveImageToPhotosAlbum:image]; } #pragma 震动实现貌似和SDK冲突 不能实现震动 //开始播放的时候调用 -(void)startPlaySystemSound{ // return; // //震动的提示文件名放到资源目录下 // NSString *path = [[NSBundle mainBundle] pathForResource:@"ring" ofType:@"wav"]; // AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &sound); //分别注册铃声和震动完后的回调 AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate, NULL, NULL, LCVibrationCompleteCallback, NULL); // AudioServicesAddSystemSoundCompletion(sound, NULL, NULL, soundCompleteCallback, NULL); AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);//开始震动 // AudioServicesPlaySystemSound(sound);//开始播放铃声 } //手动停止播放的时候调用 - (void)stopPlaySystemSound{ // return; NSLog(@"stop PlaySystemSound"); stopRingAndVibration(); } //停止响铃和震动,移除回调并处理掉铃声和震动 void stopRingAndVibration() { AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate); // AudioServicesRemoveSystemSoundCompletion(sound); AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate); // AudioServicesDisposeSystemSoundID(sound); } //震动完成回调,因为震动一下便会调用一次,这里延迟800ms再继续震动,和微信差不多,时间长短可自己控制。参数sound即为注册回调时传的第一个参数 void LCVibrationCompleteCallback(SystemSoundID sound,void * clientData) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(800 * NSEC_PER_MSEC)), dispatch_get_global_queue(0, 0), ^{ AudioServicesPlaySystemSound(sound); }); } ////铃声播放完成回调,这种方法x播放的音频限制在30秒内,播放完直接响铃和震动 //void soundCompleteCallback(SystemSoundID sound,void * clientData) { // // stopRingAndVibration(); //} /// - (void)addOpenSuccessAction { [[NSNotificationCenter defaultCenter] removeObserver:self name:LCCallDelegateOpenDoorSuccess object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setOpenDoorSuccess) name:LCCallDelegateOpenDoorSuccess object:nil]; } - (void)removeOpenSuccessAction { [[NSNotificationCenter defaultCenter] removeObserver:self name:LCCallDelegateOpenDoorSuccess object:nil]; } @end