和 iOS 的 Speech 類似, Android 也有自己的一套語音識別工具 android.speech
通過將語音轉換成文字的功能,我們可以再將文字轉換成命令。
- 提供一個按鈕用來呼叫語音輸入功能。
- 將語音識別後的文字進行判斷,
- 如果文字包含「騎車」、「爬山」、「游泳」這三個詞,就將對應的 label 改為藍色,否則為黑色。
- 如果語音識別後發現三個詞都沒有,則全部顯示黑色,並且詢問使用者想要做什麼。
- 不處理:關鍵詞重複、順序的問題,單純是為了練習語音識別庫。
Recognize speech
使用 Inent 來使用內建的語音識別功能,然後通過 intent.putExtra 來帶入一些資訊。
1 2 3 4 5 6 7 8 9 10 11 |
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
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 用來之後判斷
1 |
startActivityForResult(intent, voiceRecognitionRequestCode) |
接收語音識別結果
通過剛才設定好的 Flag 來判斷是語音識別請求的結果,並提取識識別後的內容。
1 2 3 4 5 6 7 8 9 10 11 12 |
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) } |
筆記
- 模擬器似乎無法使用麥克風。
參考
- 官方文件 – Android.Speech
- 官方文件 – RecognizerIntent
- 可以到 Github 上看對應的 Source Code