android语音识别示例
package com.angle.anglering;import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.util.ArrayList;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class AngleRingActivity extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 4321;
private Button btn_voice = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_angle_ring);
/** * 语音识别示例 . 注意:使用前需要安装语音识别程序如语音搜索。 * /
/** Called when the activity is first created. */
btn_voice = (Button) findViewById(R.id.btn_voice);
btn_voice.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
try {
// 通过Intent传递语音识别的模式,开启语音
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// 语音模式和自由形式的语音识别
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
// 提示语音开始
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "开始语音");
// 开始执行我们的intent、语音识别
startActivityForResult(intent,VOICE_RECOGNITION_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
// 找不到语音设备装置
System.out.println("找不到语音设备装置!");
e.printStackTrace();
Toast.makeText(AngleRingActivity.this,"ActivityNotFoundException", Toast.LENGTH_LONG).show();
}
}});
}
/** * 当语音结束时的回调函数onActivityResult */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// 判断是否是我们执行的语音识别
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
// 取得语音的字符
ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String resultsString = "";
for (int i = 0; i < results.size(); i++) {
resultsString += results.get(i);
}
Toast.makeText(this, resultsString, Toast.LENGTH_LONG).show();
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_angle_ring, menu);
return true;
}
}
页:
[1]