###### tags: `Android` # Android 開發 RecognizerIntent 的陷阱 Android App 中要進行語音辨識, 也就是 speech to text 的功能, 必須仰賴 [SpeechRecognizer](https://developer.android.com/reference/android/speech/SpeechRecognizer) 類別, 不過根據系統版本以及系統 App 版本組合, 藏有幾個陷阱,如果沒有注意, 就會讓語音辨識失效。 ## 靜默時間設定 `SpeechRecognizer` 可以搭配 [RecognizerIntent](https://developer.android.com/reference/android/speech/RecognizerIntent) 指定相關的設定, 其中有一項設定是 [EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS](https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS), 根據文件的說明, 它的作用是在辨識出文字後, 要等多少靜默的時間才當成是辨識結束, 不過這個設定原本似乎一直無效, 至少在我測試的以下手機中如此: |手機型號|系統版本|語音相關 App 版本| |------|--------|----| |OPPO A31|Android 9|Google 10.84.19.21.arm64| |OPPO A31|Android 9|Google 13.4.19.23.arm64| |Real me C3|Android 10|Google 10.84.19.21.arm64| |小米 A1|Android 9|Google 10.84.19.21.arm64| |Pixel 4a|Android 12|Speech Services by Google<br/>googletts.google-speech-apk_20210729.00_p0.387528199.tnt| 事實上, 在 Android 官方的[文件](https://developer.android.com/reference/android/speech/RecognizerIntent#EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS)中, 有以下這樣的說明: > Depending on the recognizer implementation, these values may have no effect. 所以沒有效用也算是正常的。但是如果把上述語音相關 App 更新到新的版本, 變成以下這樣 (實際變化的版本我不確定): |手機型號|系統版本|語音相關 App 版本| |------|--------|----| |OPPO A31|Android 9|Google 13.17.13.23.arm64| |Real me C3|Android 10|Google 13.17.13.23.arm64| |小米 A1|Android 9|Google 13.17.13.23.arm64| |Pixel 4a|Android 12|Speech Services by Google<br/>版本 googletts.google-speech-apk_20220404.02_p1.440604258| 剛剛提到的 `EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS` 它就生效了, 如果有設定這個選項, 而且時間設定比較長, 就可能因為無法持續靜默足夠的時間, 導致語音辨識時只會引發 `onPartialResults`, 不會引發 `onResults`, 無法正確取得辨識結果了。 只要移除這個設定, 就可以避免這個問題。 ## Android 11 需要特別的設定 如果你的系統是 Android 11, 根據 [Android Developers 文件](https://developer.android.com/reference/android/speech/SpeechRecognizer#createSpeechRecognizer(android.content.Context))的說明, 要在 AndroidManifest.xml 內加入以下設定: ```xml= <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="tw.com.flag"> <queries> <intent> <action android:name="android.speech.RecognitionService" /> </intent> </queries> .... </manifest> ``` 如果沒有加上以上的段落, 語音辨識功能就無法生效, 你會在 Android Studio 中看到噴出很多奇怪的錯誤訊息, 加上設定後就一切正常了。 詳細的說明可以參考[這一篇文章](https://medium.com/androiddevelopers/package-visibility-in-android-11-cc857f221cd9), 網路上[也有人被雷到](https://stackoverflow.com/questions/64319117/speechrecognizer-not-available-when-targeting-android-11)。