【发布时间】:2020-08-26 07:20:57
【问题描述】:
我已经在我的 Mac 应用中实现了 Speech to Text。它完美地工作。但是如果 Mac mini 中没有连接输入设备(麦克风),它就会崩溃。下面是我的代码
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.")
}
})
如果 macmini 中没有连接耳机,应用程序会在 node.installTap(onBus... 在上面的代码中崩溃。
所以我的问题是如何检测用户是否没有连接麦克风或有问题并停止应用程序崩溃。
【问题讨论】:
标签: swift macos speech-to-text avaudioengine