Reputation: 172
I have implemented Speech to Text in my Mac app. It works perfectly. But if no input device(microphone) is attached in Mac mini, it crashes. Below is the code I have
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 {
print("There has been an audio engine error.")
return print(error)
}
guard let myRecognizer = SFSpeechRecognizer() else {
print("Speech recognition is not supported for your current locale.")
return
}
if !myRecognizer.isAvailable {
print("Speech recognition is not currently available. Check back at a later time.")
// Recognizer is not available right now
self.delegate?.speechToTextFailed("Speech recognition is not currently available. Check back at a later time.")
return
}
self.onCheckSupportedSpeechToTextLanguage(kUserDefaults?.value(forKey: kChoosedLang) as! String)
sttTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { (timer) in
})
recognitionTask = speechRecognizer?.recognitionTask(with: request, resultHandler: { result, error in
if let result = result {
let bestString = result.bestTranscription.formattedString
var lastString: String = ""
for segment in result.bestTranscription.segments {
let indexTo = bestString.index(bestString.startIndex, offsetBy: segment.substringRange.location)
lastString = String(bestString[indexTo...])
}
print(" bestString : \(bestString)")
self.delegate?.speechToTextConvertedText(self.previousString, bestString)
self.previousString = bestString
} else if let error = error {
print("There has been a speech recognition error.")
print(error)
self.delegate?.speechToTextFailed("There has been a speech recognition error.")
}
})
if there is no headphone attached in macmini, app crashes at node.installTap(onBus... in above code.
So my question is how can I detect if user has no microphone attached or has some issue and stop app crashing.
Upvotes: 0
Views: 290
Reputation: 49
You can check input device's channel count.
if 0 < AVAudioSession.sharedInstance().inputNumberOfChannels {
// DO Somthing..
}
If there's no input devices available, that API returns 0.
Upvotes: 2