iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 23
0
Software Development

Kotlin 30 天,通過每天一個小 demo 學習 Android 開發系列 第 23

Kotlin 開發第 23天 GoogleVoice (RecognizerIntent)

GoogleVoice
和 iOS  的 Speech 類似, Android 也有自己的一套語音識別工具 android.speech

通過將語音轉換成文字的功能,我們可以再將文字轉換成命令。

  • 提供一個按鈕用來呼叫語音輸入功能。
  • 將語音識別後的文字進行判斷,
  • 如果文字包含「騎車」、「爬山」、「游泳」這三個詞,就將對應的 label 改為藍色,否則為黑色。
  • 如果語音識別後發現三個詞都沒有,則全部顯示黑色,並且詢問使用者想要做什麼。
  • 不處理:關鍵詞重複、順序的問題,單純是為了練習語音識別庫。

Recognize speech

使用 Inent 來使用內建的語音識別功能,然後通過 intent.putExtra 來帶入一些資訊。

private fun startVoiceRecognitionActivity() {
    val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)

    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Please say something")

    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)

    intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5)

    startActivityForResult(intent, voiceRecognitionRequestCode)
}

RecognizerIntent.EXTRA_PROMPT

語音輸入介面會提示的文字內容,這裡寫了 Please say something

https://ithelp.ithome.com.tw/upload/images/20171226/20107329My6sCWrJj6.png

RecognizerIntent.EXTRA_LANGUAGE_MODEL

  • RecognizerIntent.LANGUAGE_MODEL_FREE_FORM - Use a language model based on free-form speech recognition.
  • LANGUAGE_MODEL_WEB_SEARCH - Use a language model based on web search terms.

RecognizerIntent.EXTRA_MAX_RESULTS

語音識別後可以拿到多個結果,排越前面精準度越高,來一個例子:

  • 我明天早上要騎腳踏車到台南火車站
  • 我明天早上要騎腳踏車到臺南火車站
  • 我明天早上要去腳踏車到台南火車站
  • 我明天早上要騎腳踏車道台南火車站

Intent Flag

  • 搭配我們定義好的 flag 用來之後判斷
startActivityForResult(intent, voiceRecognitionRequestCode)

接收語音識別結果

通過剛才設定好的 Flag 來判斷是語音識別請求的結果,並提取識識別後的內容。

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

    if(requestCode == voiceRecognitionRequestCode && resultCode == Activity.RESULT_OK){
        val matches = data!!.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)

        // 語音識別會有多個結果,第一個是最精確的
        val text = matches.first()
        voiceTextView.setText(text)
        updateTextViewWithText(text)
    }
    super.onActivityResult(requestCode, resultCode, data)
}

筆記

  • 模擬器似乎無法使用麥克風。

參考


上一篇
Kotlin 開發第 22 天 LocalDatabase (SQLite + SQLiteOpenHelper)
下一篇
Kotlin 開發第 24 天 Painter (Canvas)
系列文
Kotlin 30 天,通過每天一個小 demo 學習 Android 開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言