android.speech.RecognizerIntent
是 Android 平台提供的一个用于语音识别的 Intent 类。它位于 android.speech
包中。
RecognizerIntent
是 Android 提供的一个标准 Intent,用于启动语音识别服务。通过这个 Intent,应用可以请求用户的语音输入,并将语音转换为文本。
RecognizerIntent
可以轻松集成语音识别功能到 Android 应用中。RecognizerIntent
是 Android 标准的一部分,它在不同设备上的兼容性较好。RecognizerIntent
主要有以下几种类型:
ACTION_RECOGNIZE_SPEECH
:用于启动语音识别服务。EXTRA_LANGUAGE_MODEL
:指定语言模型,例如 LANGUAGE_MODEL_FREE_FORM
或 LANGUAGE_MODEL_WEB_SEARCH
。EXTRA_PROMPT
:设置提示信息,显示在语音识别界面。以下是一个简单的示例代码,展示如何使用 RecognizerIntent
进行语音识别:
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE_SPEECH_INPUT = 123;
private TextView textViewResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewResult = findViewById(R.id.textViewResult);
Button buttonSpeechInput = findViewById(R.id.buttonSpeechInput);
buttonSpeechInput.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSpeechToText();
}
});
}
private void startSpeechToText() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak now");
try {
startActivityForResult(intent, REQUEST_CODE_SPEECH_INPUT);
} catch (Exception e) {
textViewResult.setText("Failed to start speech to text");
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_SPEECH_INPUT) {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
textViewResult.setText(result.get(0));
} else {
textViewResult.setText("Failed to recognize speech");
}
}
}
}
Android SpeechRecognizerIntent 文档
通过以上信息,你应该对 android.speech.RecognizerIntent
有了全面的了解,并且知道如何在 Android 应用中使用它。
领取专属 10元无门槛券
手把手带您无忧上云