您可以使用自动语音识别 (ASR) 功能,通过 SpeechRecognizer 识别用户发出的特定话语
并将其转换为文本。
SpeechRecognizer 内置于 Android 中(无需其他库),即使在离线状态下也能正常运行。
如需让 SpeechRecognizer 将用户的语音转换为文本,用户需要
向您的应用授予 RECORD_AUDIO 权限。如需了解如何为您的应用请求
此权限,请参阅请求硬件权限。
实例化 SpeechRecognizer
在投影 activity 的 projected activity's
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适用于对话语音。