您可以使用自动语音识别 (ASR) 通过 SpeechRecognizer 识别用户的特定话语,并将其转换为文本。SpeechRecognizer 已内置到 Android 中(无需其他库),即使离线也能使用。
为了让 SpeechRecognizer 将用户的语音转换为文字,用户需要向您的应用授予 RECORD_AUDIO 权限。如需了解如何为应用请求此权限,请参阅请求硬件权限。
实例化 SpeechRecognizer
在 AI 眼镜 activity 的 onCreate() 方法中实例化 SpeechRecognizer,以便在整个 activity 生命周期内使用它:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//The RECORD_AUDIO permission must be granted to your app before instantiation
speechRecognizer = SpeechRecognizer.createOnDeviceSpeechRecognizer(this)
speechRecognizer?.setRecognitionListener(recognitionListener)
...
}
配置 RecognitionListener
借助 setRecognitionListener() 方法,您可以指定用于进行重要回调的对象,例如 RecognitionListener.onResults(),系统会在识别出口头语言后调用该对象。
val recognitionListener = object : RecognitionListener {
override fun onResults(results: Bundle?) {
val matches = results?.getStringArrayList(RESULTS_RECOGNITION)
val confidences = results?.getFloatArray(CONFIDENCE_SCORES)
val mostConfidentIndex = confidences!!.indices.maxByOrNull { confidences[it] }
if (mostConfidentIndex != null){
val spokenText = matches[mostConfidentIndex]
if (spokenText.equals("Start my Run", ignoreCase = true)){
// User indicated they want to start a run
}
}
}
...
}
代码要点
系统会查询该软件包中的两个数组。第一个数组包含所有匹配项,第二个数组是语音识别器对所听到内容的置信度。这些数组的索引彼此对应。系统会使用置信度值最高的匹配项 (
mostConfidentIndex)。系统会执行不区分大小写的字符串匹配,以确定用户想要执行的操作。
匹配时的替代方法
在上面的示例中,系统会使用置信度值最高的匹配项。这意味着,系统必须对从用户那里了解到的内容有相当的把握,否则不会标记匹配项。使用此方法时,您可能会遇到假负例。
另一种方法是查看所有匹配项(无论置信度如何),并找到符合您要查找的输入内容的任何匹配项。相比之下,这种方法可能会导致更多误报。您应采取的方法很大程度上取决于您的使用情形。
开始收听
如需开始监听用户,请在调用 startListening() 时指定 ACTION_RECOGNIZE_SPEECH intent。
override fun onStart() {
super.onStart()
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
}
speechRecognizer?.startListening(intent)
}
代码要点
- 使用
ACTION_RECOGNIZE_SPEECH时,您还必须指定EXTRA_LANGUAGE_MODELextra。 LANGUAGE_MODEL_FREE_FORM适用于对话式语音。