0
目前我正在開發一個演示應用程序,並且正在被分成3個部分 1.語音到文本(完成) 2.發送文本到服務器並獲取響應返回(使用API.ai)(完成) 3.文本到語音,響應消息轉換爲語音不工作。AVSpeechsynthesizer無法在api調用中快速運行
文本到語音不是在一個函數內部工作,誰可以給它增加更多的優先級。
這裏是代碼
@IBAction func startActionTapped(_ sender: Any) {
if audioEngine.isRunning {
audioEngine.stop()
recognitionRequest?.endAudio()
startButton.isEnabled = false
startButton.setTitle("Start", for: .normal)
}
else {
startRecording()
startButton.setTitle("Stop", for: .normal)
let loadingNotification = MBProgressHUD.showAdded(to: self.view, animated: true)
loadingNotification.mode = MBProgressHUDMode.indeterminate
loadingNotification.label.text = "Voice Recogninsing...."
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
loadingNotification.label.text = "sending request to server...."
let request = ApiAI.shared().textRequest()
request?.query = ["turn on blue led"]
request?.setMappedCompletionBlockSuccess({ (request, response) in
let response = response as! AIResponse
if response.result.action == "light.led" {
if let parameters = response.result.parameters as? [String: AIResponseParameter] {
if let led = parameters["led"]?.stringValue {
switch led {
case "red":
print("color is red")
case "blue":
print("color is blue")
case "green":
print("color is green")
default:
print("color is :",led)
}
self.speechToText = ""
}
}
} else {
print("Invalid LED Color")
}
if let textResponse = response.result.fulfillment.speech {
print(textResponse)
loadingNotification.hide(animated: true)
DispatchQueue.global(qos: .userInitiated).async {
let synth = AVSpeechSynthesizer()
let utterance = AVSpeechUtterance(string: textResponse)
utterance.rate = AVSpeechUtteranceDefaultSpeechRate
let lang = "en-US"
utterance.voice = AVSpeechSynthesisVoice(language: lang)
synth.speak(utterance)
}
}
}, failure: { (request, error) in
print(error!)
})
ApiAI.shared().enqueue(request)
})
}
speechToText = ""
}
不知道爲什麼文本到語音轉換工作。 我的問題是文本到語音不適用於應用程序,我錯過了任何步驟?
let synth = AVSpeechSynthesizer()
let utterance = AVSpeechUtterance(string: textResponse)
utterance.rate = AVSpeechUtteranceDefaultSpeechRate
let lang = "en-US"
utterance.voice = AVSpeechSynthesisVoice(language: lang)
synth.speak(utterance)
嘗試在主隊列中運行代碼? – chengsam
@chengsam無法正常工作 – Joe
嘗試使用簡單的按鈕點擊事件來實現TTS,它工作嗎?在簡單的按鈕點擊 – chengsam