SpeechFramework框架简介(二)

要开发语音识别,首先要获取系统权限

捕获.PNG

通过requestAuthorization来获取权限


#import     
    //1.创建要识别的语音    
    NSLocale *local =[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];    
     //2.初始化语音识别对象    
    SFSpeechRecognizer *sfr =[[SFSpeechRecognizer alloc] initWithLocale:local];    
         
    //3.加载资源文件或者通过录音的方式来    
    NSURL *url =[[NSBundle mainBundle] URLForResource:@"*.mp3" withExtension:nil];    
    //4.将资源包中获取的url(录音文件的地址)传递给 request对象    
    SFSpeechURLRecognitionRequest *res =[[SFSpeechURLRecognitionRequest alloc] initWithURL:url];    
      //5.发送一个请求    
    [sfr recognitionTaskWithRequest:res resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {    
        if (error!=nil) {    
            NSLog(@"语音识别失败啦,%@",error);    
        }    
        else    
        {    
            //解析正确    
            NSLog(@"---%@",result.bestTranscription.formattedString);    
        }    
    }];    

也可通过代理方法来识别是否成功


//当开始检测音频源中的语音时首先调用此方法
-(void)speechRecognitionDidDetectSpeech:(SFSpeechRecognitionTask *)task;

//当识别出一条可用的信息后 会调用(void)speechRecognitionTask:(SFSpeechRecognitionTask *)task didHypothesizeTranscription:(SFTranscription *)transcription;

//识别完成
- (void)speechRecognitionTask:(SFSpeechRecognitionTask *)task didFinishRecognition:(SFSpeechRecognitionResult *)recognitionResult;

//开始处理语音,不再接受输入
(void)speechRecognitionTaskFinishedReadingAudio:(SFSpeechRecognitionTask *)task

//取消
(void)speechRecognitionTaskWasCancelled:(SFSpeechRecognitionTask *)task;

//语音识别任务完成时被调用
- (void)speechRecognitionTask:(SFSpeechRecognitionTask *)task didFinishSuccessfully:(BOOL)successfully;

你可能感兴趣的:(SpeechFramework框架简介(二))