|
1.
说明
以下例程功能为:在应用程序中使用intent来调出语言识别界面,录音并识别后将识别的字串返回给应用程序。注意:使用前需要安装语音识别程序如语音搜索。2.
本例参考自android例程:
development/samples/ApiDemos/src/com/example/android/apis/app/VoiceRecognition.java3.
可从此处下载可独立运行的代码:
三个android语音识别例程mystt.tgz.rar (13.28 KB, 下载次数: 35)
4.
核心代码及说明package com.android.mystt1;
package com.android.mystt1;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MyStt1Activity extends Activity implements OnClickListener {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
private ListView mList; // 显示识别后字串的list控件
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button speakButton = (Button) findViewById(R.id.btn_speak); // 识别按钮
mList = (ListView) findViewById(R.id.list);
PackageManager pm = getPackageManager();
List Activities = pm.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); //本地识别程序
// new Intent(RecognizerIntent.ACTION_WEB_SEARCH), 0); // 网络识别程序
if (activities.size() != 0) {
speakButton.setOnClickListener(this);
} else { // 若检测不到语音识别程序在本机安装,测将扭铵置灰
speakButton.setEnabled(false);
speakButton.setText("Recognizer not present");
}
}
public void onClick(View v) {
if (v.getId() == R.id.btn_speak) {
startMysttActivityActivity();
}
}
private void startMysttActivityActivity() { // 开始识别
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
// 调出识别界面
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
// Fill the list view with the strings the recognizer thought it could have heard
ArrayList matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
mList.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,
matches));
}
// 语音识别后的回调,将识别的字串在list中显示
super.onActivityResult(requestCode, resultCode, data);
}
} |
|