语音输入

每个 Wear OS 设备都配有麦克风,因此用户可以使用语音与设备互动。这些互动可以分为三种类型:

  • 录音
  • 获取自由格式的语音输入
  • 语音操作

录音

在 Wear OS 设备上录音的方式与在手机上录音相同。如需详细了解如何在 Android 上录音,请参阅 MediaRecorder 文档。您还可以在 GitHub 上查看 Wear 扬声器示例中的实现示例。

获取自由格式的语音输入

调用系统的内置语音识别程序 activity 来获取用户的语音输入。使用语音输入发送消息或执行搜索。

在您的应用中,使用 ACTION_RECOGNIZE_SPEECH 操作调用 startActivityForResult()。这将启动语音识别 activity,然后您可以在 onActivityResult() 中处理结果。

以下代码示例展示了如何启动和处理语音识别 activity。

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);
}

语音操作

目前不支持语音操作以及与应用有关的 Google 助理 Action,只有中国境内的 Wear OS 应用除外。详细了解中国的语音操作支持