讯飞语音识别的集成

语音识别:

  1. 创建应用,获取APPID
  2. 添加依赖库,还有content.framework
  3. bitcode的设置
  4. 引入头文件,遵循代理IFlySpeechRecognizerDelegate。
  5. 代码实现
  • 讯飞语音初始化
NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@",IFlyAppID];
    [IFlySpeechUtility createUtility:initString];
  • 初始化语音识别器
-(void)initRecognizer{
    //单例模式,无UI的实例
    if (_iFlySpeechRecognizer == nil) {
        _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];
        [_iFlySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        //设置听写模式
        [_iFlySpeechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
    }
    _iFlySpeechRecognizer.delegate = self;
    if (_iFlySpeechRecognizer != nil) {
        IATConfig *instance = [IATConfig sharedInstance];
        //设置最长录音时间
        [_iFlySpeechRecognizer setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
        //设置后端点
        [_iFlySpeechRecognizer setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
        //设置前端点
        [_iFlySpeechRecognizer setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
//设置听写模式
    [_iFlySpeechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
    _iFlySpeechRecognizer.delegate = self;
        //网络等待时间
        [_iFlySpeechRecognizer setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];
        //设置采样率,推荐使用16K
        [_iFlySpeechRecognizer setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
        if ([instance.language isEqualToString:[IATConfig chinese]]) {
            //设置语言
            [_iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
            //设置方言
            [_iFlySpeechRecognizer setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
        }else if ([instance.language isEqualToString:[IATConfig english]]) {
            [_iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
        }
        //设置是否返回标点符号
        [_iFlySpeechRecognizer setParameter:instance.dot forKey:[IFlySpeechConstant ASR_PTT]];
    }
}
  • 实现代理方法
-(void)onResults:(NSArray *)results isLast:(BOOL)isLast
{
    NSMutableString *result = [[NSMutableString alloc]init];
    NSDictionary *dic = [results objectAtIndex:0];
    for (NSString *key in dic) {
        [result appendFormat:@"%@",key];
    }
    
    NSString *resu = [ISRDataHelper stringFromJson:result];
    
    if ([resu isEqualToString:@"。"] || [resu isEqualToString:@"?"] || [resu isEqualToString:@"!"]) {
        NSLog(@"末尾标点符号:%@",resu);
        [_iFlySpeechRecognizer destroy];
    }else{
        NSLog(@"%@",resu);
        //[self createTextAndVoiceStr:resu];
        [self createTextAndVoiceStr:resu AndType:YES];
    }
}
// 出现错误
- (void) onError:(IFlySpeechError *) error
{
    NSLog(@"出现错误 :%@",error);
}
  • 点击开始和结束
// 按下录音按钮开始录音
- (void)didStartRecordingVoiceAction:(UIView *)recordView
{
    [BZGJAliAnalytics sendCustomBuilder:Ali_press_im_robot_botton];
    
    _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];
    [_iFlySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
    
    //开始录音
    BOOL ret = [_iFlySpeechRecognizer startListening];

    if (ret) {
        NSLog(@"启动成功");
    }else{
        NSLog(@"启动失败");
    }
    
    if ([self canRecord]) {
        
        DXRecordView *tmpView = (DXRecordView *)recordView;
        //tmpView.center = self.view.center;
        tmpView.frame = CGRectMake(mScreenWidth/2-70, mScreenHeight/2-70, 140, 140);
        [self.view addSubview:tmpView];
        [self.view bringSubviewToFront:recordView];
        int x = arc4random() % 100000;
        NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
        NSString *fileName = [NSString stringWithFormat:@"%d%d",(int)time,x];
        
        [[EMCDDeviceManager sharedInstance] asyncStartRecordingWithFileName:fileName
                                                                 completion:^(NSError *error)
         {
             if (error) {
                 NSLog(NSLocalizedString(@"message.startRecordFail", @"failure to start recording"));
             }
         }];
    }else{
       
        CustomAlertView *alertViewMKF = [[CustomAlertView alloc]initWithTitle:@"温馨提示!"
                                                                      message:@"请在设置->隐私中设置允许使用麦克风"
                                                                     delegate:self
                                                            cancelButtonTitle:@"取消"
                                                            otherButtonTitles:@"确定", nil];
        [alertViewMKF show];
    }
}

//手指向上滑动取消录音
- (void)didCancelRecordingVoiceAction:(UIView *)recordView
{
    //取消录音
    [_iFlySpeechRecognizer cancel];
    
    [[EMCDDeviceManager sharedInstance] cancelCurrentRecording];
}
// 松开手指完成录音
- (void)didFinishRecoingVoiceAction:(UIView *)recordView
{
    
    //停止录音开始识别
    [_iFlySpeechRecognizer stopListening];
    
    if ([self canRecord]){
        
        __weak typeof(self) weakSelf = self;
        [[EMCDDeviceManager sharedInstance] asyncStopRecordingWithCompletion:^(NSString *recordPath, NSInteger aDuration, NSError *error) {
            if (!error) {
                EMChatVoice *voice = [[EMChatVoice alloc] initWithFile:recordPath
                                                           displayName:@"audio"];
                voice.duration = aDuration;
                [weakSelf sendAudioMessage:voice];
            }else {
                [weakSelf showHudInView:self.view hint:NSLocalizedString(@"录制时间过短", @"The recording time is too short")];
                weakSelf.chatToolBar.recordButton.enabled = NO;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf hideHud];
                    weakSelf.chatToolBar.recordButton.enabled = YES;
                });
            }
        }];
    }
}

//麦克风权限
- (BOOL)canRecord
{
    __block BOOL bCanRecord = YES;
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0" options:NSNumericSearch] != NSOrderedAscending)
    {
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
            [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                bCanRecord = granted;
            }];
        }
    }
    return bCanRecord;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容