Android中主要通过RecognizerIntent来实现语音识别,其实代码比较简单,但是如果找不到设置,就会抛出异常 ActivityNotFoundException,所以我们需要捕捉这个异常。而且语音识别在模拟器上是无法测试的,因为语音识别是访问google 云端数据,所以如果手机的网络没有开启,就无法实现识别声音的!一定要开启手机的网络,如果手机不存在语音识别功能的话,也是无法启用识别!

下面是RecognizerIntentActivity中的代码:

查看源码
01 public class RecognizerIntentActivity extends Activity {
02
03 private Button btnReconizer;
04 private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
05 @Override
06 protected void onCreate(Bundle savedInstanceState) {
07 // TODO Auto-generated method stub
08 super.onCreate(savedInstanceState);
09 setContentView(R.layout.reconizer);
10
11 btnReconizer=(Button) this.findViewById(R.id.btnRecognizer);
12 btnReconizer.setOnClickListener(new OnClickListener() {
13
14 @Override
15 public void onClick(View v) {
16 // TODO Auto-generated method stub
17 try{
18 //通过Intent传递语音识别的模式,开启语音
19

Intent intent=new Intent

(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

20 //语言模式和自由模式的语音识别
21

intent.putExtra(

RecognizerIntent.EXTRA_LANGUAGE_MODEL,

RecognizerIntent.LANGUAGE_MODEL_FREE_FORM

);

22 //提示语音开始
23 intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "开始语音");
24 //开始语音识别
25

startActivityForResult(

intent,

VOICE_RECOGNITION_REQUEST_CODE

);

26 }catch (Exception e) {
27 // TODO: handle exception
28 e.printStackTrace();
29

Toast.makeText(

getApplicationContext(),

"找不到语音设备",

1).show();

30 }
31 }
32 });
33
34 }
35
36 @Override
37

protected void onActivityResult(

int requestCode,

int resultCode,

Intent data) {

38 // TODO Auto-generated method stub
39 //回调获取从谷歌得到的数据
40

if(requestCode==VOICE_RECOGNITION_REQUEST_CODE

&& resultCode==RESULT_OK){

41 //取得语音的字符
42

ArrayList results=data.getStringArrayListExtra

(RecognizerIntent.EXTRA_RESULTS);

43
44 String resultString="";
45 for(int i=0;i
46 resultString+=results.get(i);
47 }
48 Toast.makeText(this, resultString, 1).show();
49 }
50 super.onActivityResult(requestCode, resultCode, data);
51 }
52 }

 

其主要原理就是将语音发送到google云端,然后云端处理,匹配相应的数据,发送到客户端。

最后不要忘记,在manifest中加入网络访问权限:


运行后效果:
点击开始语音按钮,然后开始说话(这里要保证手机的网路是打开的):

更多相关文章

  1. Android(安卓)轻松实现语音识别
  2. Android(安卓)实现语音识别的完整代码
  3. Android(安卓)Studio 初体验
  4. Android应用层源码阅读笔记--Application
  5. Android(安卓)实现语音识别
  6. Android中使用语音引擎入门七步曲
  7. Android中使用语音引擎入门七步曲
  8. Android中使用语音引擎入门七步曲
  9. android实现一天24小时刻度尺

随机推荐

  1. Android使用代码模拟HOME键的功能
  2. 35、键盘布局的tableLayout备份
  3. Android(安卓)Gallery子元素无法横向填满
  4. Android植物大战僵尸小游戏
  5. android返回HOME界面
  6. android textview部分字体变颜色
  7. android自带图片资源
  8. Android 珍藏(三)
  9. Android系统工具之Monkey自动化测试
  10. Android菜单实例