1、先晒晒效果图:
2、manifest 文件访问网络配置:
<uses-permission Android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
3、layout配置文件代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
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" >
<requestFocus />
</EditText>
<Button
android:id="@+id/btnStartVoiceInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/sensor_voice_input_btn_startinput" />
</LinearLayout>
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<String> 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()来接听文本结果。