【发布时间】:2019-05-31 00:18:57
【问题描述】:
我正在使用 SpriteKit 构建一个应用程序。 Scene 的其他功能都是通过 SpriteKit 完成的。我想将语音识别添加到场景中,以便当用户触摸麦克风按钮节点时,他们说的单词与他们需要说的正确单词匹配以继续前进。这在 SpriteKit 上可行吗?下面的代码是我正在使用的函数,但它不会导致任何事情发生。
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.")
// Recognizer is not available right now
return
}
recognitionTask = speechRecognizer?.recognitionTask(with: request, resultHandler: { result, error in
if let result = result {
let bestString = result.bestTranscription.formattedString
self.labelNode.text = bestString
var lastString: String = ""
for segment in result.bestTranscription.segments {
let indexTo = bestString.index(bestString.startIndex, offsetBy: segment.substringRange.location)
lastString = bestString.substring(from: indexTo)
}
self.checkPhrase(resultString: lastString)
} else if let error = error {
self.sendAlert(message: "There has been a speech recognition error.")
print(error)
}
})
}
下面是我在触摸麦克风节点时使用的代码,当我运行它时没有任何反应:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let location = touch.location(in: self)
if micButton.contains(location) {
if isRecording == true {
audioEngine.stop()
recognitionTask?.cancel()
isRecording = false
} else {
self.recordAndRecognizeSpeech()
isRecording = true
}
}
【问题讨论】:
-
是的,有可能
-
我无法获取代码来请求在 Spritekit 中使用麦克风的权限,但是当我在 UIKit 上使用几乎相同的代码时它可以工作。两者在语音识别工作方面是否存在重大差异?
标签: swift xcode sprite-kit