前提:
1.安装谷歌语音搜索APP
2.需要越狱连接外网
废话不多说,直接上代码
public void onClick(View v) {
//开启语音识别功能
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
//设置模式,这里设置成自由模式
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
//提示语音开始文字
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"Please start your voice");
//开始进行语音识别,这里先检测手机(模拟器)是否支持语音识别并且捕获异常
try {
startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Opps! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
}
});
使用onActivityResult接收返回的结果
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && data != null) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
//这里集合列表中第一个值为匹配度最高的值
txtText.setText(text.get(0));
}
break;
}
}
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/txtText"
android:gravity="center"
android:orientation="vertical">
<EditText
android:id="@+id/txtText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="left"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:hint="@string/edit"/>
<ImageButton
android:id="@+id/btnSpeak"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:contentDescription="@string/speak"
android:src="@android:drawable/ic_btn_speak_now"/>
</LinearLayout>