检查答案: https://dev59.com/nFgQ5IYBdhLWcg3wlk_P#42925643
声明一个 String
变量来存储识别出的单词。
Timer
:strWords = ""
var timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "didFinishTask", userInfo: nil, repeats: false)
recognitionTaskWithRequest
块中添加以下代码:strWords = result.bestTranscription.formattedString
didFinishTalk
,则:if strWords == "" {
timer.invalidate()
timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "didFinishTalk", userInfo: nil, repeats: false)
} else {
// 使用 "strWord" 进行操作
}
尽管这个帖子很旧了,但我可能有一些好的结果可以分享给路过的任何人。
我使用的“技巧”是实际上让一个字母对应于一个“词语”或类似的内容:
recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
guard let recognitionRequest = recognitionRequest else { fatalError("Unable to create a SFSpeechAudioBufferRecognitionRequest object") }
recognitionRequest.shouldReportPartialResults = true
// Associate a letter to a word or an onomatopoeia
var letters = ["Hey": "A",
"Bee": "B",
"See": "C",
"Dee": "D",
"He": "E",
"Eff": "F",
"Gee": "G",
"Atch": "H"]
// This tells the speech recognition to focus on those words
recognitionRequest.contextualStrings = letters.key
然后,在recognitionTask
中接收音频时,我们访问字典以检测单词与哪个字母相关联。
recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest) { result, error in
var isFinal = false
if let result = result {
isFinal = result.isFinal
let bestTranscription = result.bestTranscription
// extract the confidence the recognizer has in this word
let confidence = bestTranscription.segments.isEmpty ? -1 : bestTranscription.segments[0].confidence
print("Best \(result.bestTranscription.formattedString) - Confidence: \(confidence)")
// Only keep results with some confidence
if confidence > 0 {
// If the transcription matches one of our keys we can retrieve the letter
if letters.key.map({ $0.lowercased() }) .contains(result.bestTranscription.formattedString.lowercased()) {
let detected = result.bestTranscription.formattedString
print("Letter: \(letters[detected])")
// And stop recording afterwards
self.stopRecording()
}
}
}
if error != nil || isFinal {
// The rest of the boilerplate from Apple's doc sample probect...
}
}
注意:
shouldReportPartialResults
设置为true非常重要,否则它会在发送结果之前等待相当长的时间。recognitionRequest.contextualStrings
时,当它识别出其中一个字符串时,置信度往往会飙升。您可以将置信度阈值提高到0.3或0.4。一些结果:
Best Gee - Confidence: 0.0
// ... after a while, half a second maybe ...
Best Gee - Confidence: 0.864
Found G
(苹果的示例项目用于测试:https://developer.apple.com/documentation/speech/recognizing_speech_in_live_audio)