語(yǔ)音識(shí)別系統(tǒng)是基于系統(tǒng)的speech.framework來實(shí)現(xiàn)的
寫的demo已經(jīng)上傳github:
1. 首先,獲取授權(quán)
// Privacy - Speech Recognition Usage Description 錄音權(quán)限
// Privacy - Microphone Usage Description 話筒權(quán)限
2. 基本類
@property (strong, nonatomic)SFSpeechRecognitionTask *recognitionTask; //語(yǔ)音識(shí)別任務(wù)
@property (strong, nonatomic)SFSpeechRecognizer *speechRecognizer; //語(yǔ)音識(shí)別器
@property (strong, nonatomic)SFSpeechAudioBufferRecognitionRequest *recognitionRequest; //識(shí)別請(qǐng)求
@property (strong, nonatomic)AVAudioEngine *audioEngine; //錄音引擎
3. 開啟識(shí)別任務(wù)
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(@"當(dāng)前識(shí)別內(nèi)容是: %@",nowString);
}else{
self.sentenceSpeechHandler(self, bestString);
}
}
if (self.allSpeechHandler) {
self.allSpeechHandler(self, [bestString copy]);
}
self.lastString = bestString;
NSLog(@"進(jìn)行了一次語(yǔ)音識(shí)別,內(nèi)容是: %@",bestString);
}
if (error || isFinal) {
[self.audioEngine stop];
[inputNode removeTapOnBus:0];
self.recognitionRequest = nil;
self.recognitionTask = nil;
//self.siriBtu.enabled = true;
}
}];