今天从网上找了个例子实现了语音识别,个人感觉挺好玩的,就把代码贴出来与大家分享下:
Android中主要通过RecognizerIntent来实现语音识别,其实代码比较简单,但是如果找不到设置,就会抛出异常ActivityNotFoundException,所以我们需要捕捉这个异常。而且语音识别在模拟器上是无法测试的,因为语音识别是访问google云端数据,所以如果手机的网络没有开启,就无法实现识别声音的!一定要开启手机的网络,如果手机不存在语音识别功能的话,也是无法启用识别!
下面是RecognizerIntentActivity中的代码:
public class RecognizerIntentActivity extends Activity { private Button btnReconizer; private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.reconizer); btnReconizer=(Button) this.findViewById(R.id.btnRecognizer); btnReconizer.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub 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, "开始语音"); //开始语音识别 startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); Toast.makeText(getApplicationContext(), "找不到语音设备", 1).show(); } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub //回调获取从谷歌得到的数据 if(requestCode==VOICE_RECOGNITION_REQUEST_CODE && resultCode==RESULT_OK){ //取得语音的字符 ArrayList<String> results=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); String resultString=""; for(int i=0;i<results.size();i++){ resultString+=results.get(i); } Toast.makeText(this, resultString, 1).show(); } super.onActivityResult(requestCode, resultCode, data); } }