Used the nice code in this tutorial! with some corrections. The speech recognition code is working. But if I trigger the the recognition code more than twice, the error in the title pops up. Hard finding documentation that addresses this. Anyone?
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)
}
}
})
}
The following is the function that starts and stops recognizer.
/// 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
}
}