每部 Wear OS 裝置都有麥克風,可讓使用者透過語音和裝置互動。互動方式可分為三種類型:
- 錄音
- 取得任意形式的語音輸入
- 語音操作
錄音
在 Wear OS 裝置上錄音的方法和手機相同。請參閱 MediaRecorder 文件深入瞭解如何在 Android 裝置錄音。您也可以前往 GitHub 的 Wear Speaker 範例查看實作範例。
取得任意形式的語音輸入
請呼叫系統內建的 Speech Recognizer 活動取得使用者的語音輸入內容。使用語音輸入內容傳送訊息或搜尋內容。
在應用程式中使用 ACTION_RECOGNIZE_SPEECH
動作呼叫 startActivityForResult()
。這樣做便會啟動語音辨識活動,您可以在 onActivityResult()
處理結果。
以下程式碼範例將說明如何啟動和管理語音辨識活動。
Kotlin
private const val SPEECH_REQUEST_CODE = 0 ... // Create an intent that can start the Speech Recognizer activity private fun displaySpeechRecognizer() { val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply { putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) } // This starts the activity and populates the intent with the speech text. startActivityForResult(intent, SPEECH_REQUEST_CODE) } // This callback is invoked when the Speech Recognizer returns. // This is where you process the intent and extract the speech text from the intent. override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) { if (requestCode == SPEECH_REQUEST_CODE && resultCode == Activity.RESULT_OK) { val spokenText: String? = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS).let { results -> results[0] } // Do something with spokenText. } super.onActivityResult(requestCode, resultCode, data) }
Java
private static final int SPEECH_REQUEST_CODE = 0; // Create an intent that can start the Speech Recognizer activity private void displaySpeechRecognizer() { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); // This starts the activity and populates the intent with the speech text. startActivityForResult(intent, SPEECH_REQUEST_CODE); } // This callback is invoked when the Speech Recognizer returns. // This is where you process the intent and extract the speech text from the intent. @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == SPEECH_REQUEST_CODE && resultCode == RESULT_OK) { List<String> results = data.getStringArrayListExtra( RecognizerIntent.EXTRA_RESULTS); String spokenText = results.get(0); // Do something with spokenText. } super.onActivityResult(requestCode, resultCode, data); }
語音操作
中國境內除了 Wear OS 應用程式之外,目前尚未支援語音操作及 Google 助理應用程式操作。詳情請見「中國的語音操作支援」。