Android精选Android 开发Android开发经验谈

Google 语音识别

2020-03-20  本文已影响0人  BugFree张瑞

过程如下:

  1. 启动语音识别 Activity
  2. 这里处理语音(传到 google 服务器处理)
  3. 结果以 Acitivity 的结果返回(onActivityResult)
private fun googleVoiceDemo() {
    // ACTION_RECOGNIZE_SPEECH:一般语音识别,在这种模式下我们可捕捉到语音的处理后的文字列
    // ACTION_WEB_SEARCH:网络搜索
    val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
    // Display an hint to the user about what he should say.
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "请说标准普通话")
    // Given an hint to the recognizer about what the user is going to say
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)

    // Specify how many results you want to receive. The results will be sorted
    // where the first result is the one with higher confidence.
    intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5) // 通常情况下,第一个结果是最准确的。
    startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
        // Fill the list view with the strings the recognizer thought it could have heard
        val matches = data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)?.toList()

        val stringBuilder = StringBuilder()

        matches?.forEach {
            stringBuilder.append(it).append("\n")
        }
        recognize_result.text = stringBuilder
    }
    super.onActivityResult(requestCode, resultCode, data)
}
上一篇 下一篇

猜你喜欢

热点阅读