语音识别系统是基于系统的speech.framework来实现的
写的demo已经上传github:
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;
}
}];