package com.seeol.speech;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.widget.EditText;
import android.widget.Toast;
/**
* 语音识别
* @author linchunda
*
*/
public class MainActivity extends Activity {
private final static int REQUEST_RECOGNIZE = 100;
private EditText edit_edittext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit_edittext = (EditText) findViewById(R.id.edit_edittext);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
//EXTRA_LANGUAGE_MODEL帮助优化语音识别器的处理结果
//典型的语音到文本的识别应该用LANGUAGE_MODEL_FREE_FORM
//如果较短的识别,RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
//EXTRA_PROMPT提示用户开始语音识别的字符串
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Tell me your name");
try {
startActivityForResult(intent, REQUEST_RECOGNIZE);
} catch (Exception e) {
//没有语音识别,从市场下载
AlertDialog.Builder builder= new AlertDialog.Builder(this);
builder.setTitle("No Available");
builder.setMessage("There is currently no recognition application installed."
+ "would you like to download one?");
builder.setPositiveButton("yes", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent marketIntent = new Intent(Intent.ACTION_VIEW);
marketIntent.setData(Uri.parse("market://details?id=com.google.android.voicesearch"));
}
});
builder.setNegativeButton("No", null);
builder.create().show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_RECOGNIZE
&& resultCode == Activity.RESULT_OK) {
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
StringBuffer sb = new StringBuffer();
for (String string : matches) {
sb.append(string);
sb.append('\n');
}
edit_edittext.setText(sb.toString());
} else {
Toast.makeText(this, "操作取消", Toast.LENGTH_LONG).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}