1、先晒晒效果图:
2、manifest 文件访问网络配置:
3、layout配置文件代码:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
android:id="@+id/txtVoiceInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/sensor_voice_input_lb_title" >
android:id="@+id/btnStartVoiceInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/sensor_voice_input_btn_startinput" />
4、Java代码:
private Button btnStartVoiceInput;
private int InputResultCode = 1;
private EditText txtVoiceInput;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sensor_voice_input);
//开始语音输入按钮绑定
txtVoiceInput = (EditText)findViewById(R.id.txtVoiceInput);
btnStartVoiceInput = (Button)findViewById(R.id.btnStartVoiceInput);
btnStartVoiceInput.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//调用系统传感器语音输入Api
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
//必须输入项语言模式
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, InputResultCode);
txtVoiceInput.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"抱歉您的系统不支持语音识别输入。",
Toast.LENGTH_LONG);
t.show();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == InputResultCode && resultCode == RESULT_OK && data != null) {
//获取解析的结果
ArrayList voiceList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtVoiceInput.setText(voiceList.get(0));
}
}
Android Speech to text Android API的核心是包 android.speech和类 android.speech.RecognizerIntent。我们触发一个意图(android.speech.RecognizerIntent)显示对话框来识别语音输入,这个Activity转换语音为文本并把结果传回我们正在调用的Activity。当我们调用android.speech.RecognizerIntent意图时,必须使用 startActivityForResult()来接听文本结果。
注意在上面的代码中我们是怎样创建并触发意图intent android.speech.RecognizerIntent的,同时使用.putExtra()方法添加了一个参数。调用RecognizerIntent时,必须提供RecognizerIntent.EXTRA_LANGUAGE_MODE,在这里我们设置为 en-US。
由于我们的RecognizerIntent通过startActivityForResult()触发,我们重写了 onActivityResult(int requestCode, int resultCode, Intent data)方法来处理结果数据。RecognizerIntent会把语音转换为文本并把结果通过键RecognizerIntent.EXTRA_RESULTS作为ArrayList传回来。只有RESULT_OK返回时才会出现。我们只需要使用 txtText.setText()把从结果中拿到的文本设置到text view texText中。
在这里值得注意的一件事是在不支持speech to text API的设备/Android版本中应该怎样处理。在这种情况下,当我们视图启动Activity时ActivityNotFoundException异常会被抛出。