您的位置:首页 > 移动开发 > Android开发

android语音识别方法一:使用intent调用语音识别程序

2010-08-03 13:26 716 查看
1. 说明
以下例程功能为:在应用程序中使用intent来调出语言识别界面,录音并识别后将识别的字串返回给应用程序。注意:使用前需要安装语音识别程序如语音搜索。
2. 本例参考自android例程:
development/samples/ApiDemos/src/com/example/android/apis/app/VoiceRecognition.java
3. 可从此处下载可独立运行的代码:
http://download.csdn.net/source/2591401
4. 核心代码及说明
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);
}
}

(转载请注明出处: http://xy0811.spaces.live.com/)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐