JLChen
2021-04-01 bf7f42bc3b63a0c2cec5a5adfb44feffab47a077
SDKDemo/ESVideoPhoneSDKDemo_F20210315/ESVideoPhoneSDKDemo/ViewController.mm
File was renamed from ESVideoPhoneSDKDemo1.2/ESVideoPhoneSDKDemo/ESVideoPhoneSDKDemo/ViewController.mm
@@ -16,16 +16,15 @@
 添加系统库 libiconv2.4.0.tbd,libz.tbd,libbz2.tbd.
 3、demo仅做参考,具体请根据App的情况适时调用
 */
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <AVFoundation/AVFoundation.h>
#import "ViewController.h"
#import <ESVideoPhoneSDk/ESVideoPhone.h>
#import <ESVideoPhoneSDk/ESError.h>
#import "AudioSessionHelper.h"
#import "ESVideo.h"
@interface ViewController ()<ESVideoPhoneDelegate,UITextFieldDelegate>
@property (nonatomic,strong) AudioSessionHelper    *sessionHelper;
@property (nonatomic,strong) ESVideoPhone          *es;
@property (nonatomic,assign) BOOL                  playing;
@property (nonatomic,assign) BOOL                  isInterrupt;
@@ -35,38 +34,32 @@
@property (weak, nonatomic) IBOutlet UITextField *uIDTextField;
@property (weak, nonatomic) IBOutlet UIButton *mCallOrAccept;
@property (weak, nonatomic) IBOutlet UIButton *monitorBtn;
@property (weak, nonatomic) IBOutlet UITextField *mngUUIDTextField;
@end
@implementation ViewController
{
    BOOL isAccessAudio;
    BOOL isAccessVideo;
    BOOL isBackGround;
    BOOL iSVideoNotDetermined;
    BOOL iSAudioNotDetermined;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [ESVideo.shareInstance initSDK];
    [self testHttp];
    //初始化中断,进入后台的tag
    _playing = NO;
    _isSpeaking = NO;
    _isSpeaking = YES;
    self.isInterrupt = NO;
    _es = ESVideo.shareInstance.es;
    _es.isInterrupt = NO;
    isBackGround = NO;
    [_speakerBtn setTitle:@"听筒" forState:UIControlStateNormal];
//    _mCallOrAccept.enabled = NO;
//    _monitorBtn.enabled = NO;
//    _uIDTextField.text = @"JJY000016YWECG";//@"JJY000007FSEYX" 默认门口机的ID
//       _uIDTextField.text = @"JJY000017XLUXX";//@"JJY000007FSEYX" 默认门口机的ID
    _uIDTextField.text = @"JJY000019VPLLF";//@"JJY000019VPLLF" 默认门口机的ID
//           _uIDTextField.text = @"JJY000016YWECG";//@"JJY000016YWECG" 默认门口机的ID
    _uIDTextField.text = @"JJY000019VPLLF"; //@"JJY000016YWECG";//@"JJY000007FSEYX" 默认门口机的ID
    _uIDTextField.delegate = self;    //⚠️这里必须要检查是否已经授权否则会失败,初始化视频音频采集
    [self requestAccessForAVMediaType:AVMediaTypeAudio];
     if (isAccessAudio) {
@@ -77,21 +70,16 @@
                 [self saveImage:image];
             });
         };
         //门口机会有视频的长宽高,是固定的(暂时还不确定)
//         _es = [[ESVideoPhone alloc]initESVideoPhoneWithFrame:CGRectMake(10, 100, self.view.frame.size.width-20, (self.view.frame.size.width-20)/4*3) delegate:self imagecallBack:snapImageCallback];
         //门口机会有视频的长宽高,是固定的(暂时还不确定),
         _es = [[ESVideoPhone alloc]initESVideoPhoneWithFrame:CGRectMake(10, 100, self.view.frame.size.width-20, (self.view.frame.size.width-20)/4*3) delegate:self imagecallBack:snapImageCallback];
         if (_es) {
             //判断视频渲染是否初始化成功,如果失败会走ESVideoPhoneDelegate方法
             if (_es.showView) {
//                 _es.showView.frame = CGRectMake(10, 100, self.view.frame.size.width-20, (self.view.frame.size.width-20)/4*3);
                 ESVideo.shareInstance.snapImageCallback = snapImageCallback;
                 _es.showView.backgroundColor = [UIColor greenColor];
                 _es.delegate = self;
                 [self.view addSubview:_es.showView];
             }else{
                 NSLog(@"_es.showView null");
             }
         }else{
             //p2p初始化失败会返回nil
             NSLog(@"ESVideoPhone 初始化失败");
             return;
         }
@@ -110,14 +98,46 @@
            NSLog(@"VideoCaptureSession 初始化失败");
        }
    }
    //初始化AudioSession
    _sessionHelper = [[AudioSessionHelper alloc]init];
    [_sessionHelper setAudioSession];
    //添加进入后台,中断等通知
    [self addObservers];
    [self internetStatus];
    NSLog(@"%@", [self getIpAddress]);
}
-(void)internetStatus {
    NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];//此处修改为自己公司的服务器地址
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (error == nil) {
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
                NSLog(@"%@",dict);
            }
        }];
        [dataTask resume];
}
-(void)testHttp
{
    NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];//此处修改为自己公司的服务器地址
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            NSLog(@"网络请求测试%@",dict);
        }else{
            NSLog(@"网络请求测试失败");
        }
    }];
    [dataTask resume];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    //这个方法请根据App的具体情况调用
    //在viewDidLoad中 调用requestAccessForAVMediaType: 是为了节约初始化的时间
    //在viewDidAppear中调用requestAccessForAVMediaType: 是为了弹出提示打开权限的Alert
@@ -138,61 +158,64 @@
    [_es stopTalk];
}
-(void)dealloc{
    _es.delegate = nil;
//    _es.showView
      NSLog(@"==============dealloc1");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
      NSLog(@"==============dealloc2");
//    [_es freeSubClass];
      NSLog(@"==============dealloc3");
    [_es freeSubClass];
}
#pragma mark ButtonAction
- (IBAction)back:(id)sender {
    [self dismissViewControllerAnimated:YES completion:NULL];
}
//反呼:模拟门口机呼叫手机,需要门口机先点呼叫,等1-2S后,手机点反呼。
//params样本 address=192.168.1.3:8554,tag=mobile://123,
//params样本 address=JJY000003UYRBK,tag=mobile://123,
- (IBAction)onReverseCall:(id)sender {
    NSString *title = [sender titleForState:UIControlStateNormal];
    if ([title isEqualToString:@"反呼"]) {
       NSString *normalStr = _uIDTextField.text;
       NSString *param = [NSString stringWithFormat:@"address=%@,tag=mobile://123,",normalStr];
       NSLog(@"============点反呼%@", param);
       //NSLog(@"%@", param);
       [_es onReverseCall:param];
    }else if([title isEqualToString:@"接听"]){
        [_es onAccept];
       [_es onAccept];
    }
  
}
- (IBAction)onHangup:(id)sender {
    [_es onHangup];
}
- (IBAction)onCallMng:(UIButton *)sender {
    [_es onCall:_mngUUIDTextField.text];
}
- (IBAction)onMonitor:(id)sender {
    [_es onMonitor:_uIDTextField.text];
}
- (IBAction)speaker:(UIButton *)sender {
    [_es stopTalk];
      NSString *result = nil;
      //听筒状态 插耳塞后拔掉后恢复到默认设置
      if (sender == nil) {
          result = [_sessionHelper speaker:NO];
          //result = [_sessionHelper speaker:YES];
          if ([_es resetAudioCaptureIsSpeak:YES]) {
              result = @"听筒";
          }
      }else{
          if(!_isSpeaking){
              result = [_sessionHelper speaker:YES];
            //  result = [_sessionHelper speaker:YES];
              [_es resetAudioCaptureIsSpeak:YES];
              result = @"听筒";
              _isSpeaking = YES;
          }else{
              result = [_sessionHelper speaker:NO];
             // result = [_sessionHelper speaker:NO];
              [_es resetAudioCaptureIsSpeak:NO];
              result = @"免提";
              _isSpeaking = NO;
          }
      }
      if (result) {
          [sender setTitle:result forState:UIControlStateNormal];
          [_es startTalk];
      }
}
- (IBAction)openDoor:(id)sender {
@@ -279,7 +302,7 @@
    // If media services were reset, and the last start succeeded, restart the session.
    if (error.code == AVErrorMediaServicesWereReset) {
        [_es onStopCapture];
        [_es startTalk];
        [_es stopTalk];
    }
}
@@ -577,4 +600,30 @@
    
}
-(NSString *)getIpAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}
@end