iOS开发 基于系统原生的语音识别助手

语音识别系统是基于系统的speech.framework来实现的

写的demo已经上传github:

git地址->

1. 首先,获取授权

//  Privacy - Speech Recognition Usage Description      录音权限
//  Privacy - Microphone Usage Description              话筒权限

2. 基本类

@property (strong, nonatomic)SFSpeechRecognitionTask *recognitionTask; //语音识别任务
@property (strong, nonatomic)SFSpeechRecognizer *speechRecognizer; //语音识别器
@property (strong, nonatomic)SFSpeechAudioBufferRecognitionRequest *recognitionRequest; //识别请求
@property (strong, nonatomic)AVAudioEngine *audioEngine; //录音引擎

3. 开启识别任务

 self.recognitionTask = [self.speechRecognizer recognitionTaskWithRequest:self.recognitionRequest resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
        bool isFinal = false;
        if (result) {
            NSString * bestString = [[result bestTranscription] formattedString];
            isFinal = [result isFinal];
            if(self.sentenceSpeechHandler){
                if(self.lastString && self.lastString.length>0){
                    //获取最后一句话
                    NSRange range = [bestString rangeOfString:self.lastString];
                    NSString * nowString = [bestString substringFromIndex:range.length];
                    self.sentenceSpeechHandler(self, nowString);
                    NSLog(@"当前识别内容是: %@",nowString);
                }else{
                    self.sentenceSpeechHandler(self, bestString);
                }
            }
            if (self.allSpeechHandler) {
                self.allSpeechHandler(self, [bestString copy]);
            }
            self.lastString = bestString;
            NSLog(@"进行了一次语音识别,内容是: %@",bestString);
        }
        if (error || isFinal) {
            [self.audioEngine stop];
            [inputNode removeTapOnBus:0];
            self.recognitionRequest = nil;
            self.recognitionTask = nil;
            //self.siriBtu.enabled = true;
        }
    }];

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容