在本教程中使用了漂亮的代码!有一些更正。语音识别代码正在工作。但是如果我触发识别码两次以上,就会弹出标题中的错误。很难找到解决这个问题的文档。任何人?
private func recordAndRecognizeSpeech()
{
let node = audioEngine.inputNode
let recordingFormat = node.outputFormat(forBus: 0)
node.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { buffer, _ in
self.request.append(buffer)
}
audioEngine.prepare()
do {
try audioEngine.start()
}
catch {
self.sendAlert(message: "There has been an audio engine error.")
return print (error)
}
guard let myRecognizer = SFSpeechRecognizer() else
{
self.sendAlert(message: "Speech recognition is not supported for your current locale.")
return
}
if !myRecognizer.isAvailable
{
self.sendAlert(message: "Speech recognition is not currently available. Check back at a later time.")
return
}
recognitionTask = speechRecognizer?.recognitionTask(with: request, resultHandler:
{ result, error in
if result != nil
{
if let result = result
{
let bestString = result.bestTranscription.formattedString
self.detectedTextLabel.text = bestString
}
else if let error = error
{
self.sendAlert(message: "There has been a speech recognition error.")
print(error)
}
}
})
}
Run Code Online (Sandbox Code Playgroud)
下面是启动和停止识别器的函数。
/// This button is the toggle for Starting and Stopping the Speech Recognition function
@objc func didTapSpeechButton()
{
if isRecording == true {
print("--> Stop Recording.")
request.endAudio() // Mark end of recording
audioEngine.stop()
let node = audioEngine.inputNode
node.removeTap(onBus: 0)
recognitionTask?.cancel()
isRecording = false
speechButton.backgroundColor = UIColor.red
} else {
print("--> Start Recording.")
self.recordAndRecognizeSpeech()
isRecording = true
speechButton.backgroundColor = UIColor.gray
}
}
Run Code Online (Sandbox Code Playgroud)
找到了可能的答案,因此决定分享。其他人可能会发现它很有用。这被添加到函数 recordAndRecognizeSpeech() 中。
错误是显而易见的,但解决方案对于我们学习来说却并非如此。应用程序没有崩溃。如果存在更好的答案 - 希望其他人可以提供帮助。
// This resets the recognitionRequest so "...cannot be re-use..." error is avoided.
recognitionRequest = SFSpeechAudioBufferRecognitionRequest() // recreates recognitionRequest object.
guard let recognitionRequest = recognitionRequest else { fatalError("Unable to created a SFSpeechAudioBufferRecognitionRequest object") }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2037 次 |
最近记录: |