如何无需启停SFSpeechRecognizer识别,从SFSpeechRecognitionResult获取最后说出的单词
SFSpeechRecognizer 获取最新识别单词及实现擦除功能方案
- 无需停止或重启识别即可获取最后说出的单词:
SFSpeechRecognitionResult的bestTranscription属性除了拼接好的完整字符串formattedString外,还提供了segments数组,数组中每一个元素都是SFTranscriptionSegment类型,对应拆分后的单个识别词汇/短语,直接取数组最后一个元素的substring属性即可得到最新识别到的单词。 - 擦除最后输入内容的实现逻辑:在本地维护一个可变数组存储已经确认的识别片段,每次识别回调返回结果时,通过
result.isFinal判断当前结果是否为最终确认结果,确认后将对应片段同步到本地数组。需要执行擦除操作时,直接移除本地数组的最后一个元素,再将剩余元素拼接为完整文本即可。
你可以将原有代码中识别回调的结果处理部分修改为以下逻辑:
recognitionTask = [speechRecognizer recognitionTaskWithRequest:_SFSpeechAudioBufferRecRequest resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) { if (result) { // 获取拆分后的所有识别片段 NSArray *currentSegments = result.bestTranscription.segments; // 取最后一个识别到的单词 SFTranscriptionSegment *lastSegment = currentSegments.lastObject; NSString *lastSpokenWord = lastSegment.substring; NSLog(@"最新识别单词:%@",lastSpokenWord); NSLog(@"完整识别结果:%@",result.bestTranscription.formattedString); // 擦除功能配套逻辑:结果最终确认后同步到本地数组 if (result.isFinal) { self.confirmedSegments = [NSMutableArray arrayWithArray:currentSegments]; } } if (error) { NSLog(@"ERROR %@", error); @try { [audioEngine stop]; [inputNode removeTapOnBus:0]; _SFSpeechAudioBufferRecRequest = nil; recognitionTask = nil; } @catch (NSException *exception) { NSLog(@"EXCEPTION ======== %@",exception); } @finally { } } }];
擦除操作的示例实现:
- (void)eraseLastContent { if (self.confirmedSegments.count > 0) { [self.confirmedSegments removeLastObject]; // 重新拼接完整文本 NSMutableString *newFullText = [NSMutableString string]; for (SFTranscriptionSegment *seg in self.confirmedSegments) { [newFullText appendString:seg.substring]; // 可根据需求自行加空格等分隔符 } NSLog(@"擦除后的完整文本:%@", newFullText); } }
内容的提问来源于stack exchange,提问作者Siva
相关产品推荐
相关产品推荐

