现在的位置: 首页 > 综合 > 正文

android语音识别技术

2018年01月10日 ⁄ 综合 ⁄ 共 2013字 ⁄ 字号 评论关闭

android语音识别技术

分类: android中级
2012-02-11 23:35 1217人阅读 评论(0) 收藏 举报

今天从网上找了个例子实现了语音识别,个人感觉挺好玩的,就把代码贴出来与大家分享下:

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

下面是RecognizerIntentActivity中的代码:

[html] view plain
copy

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);
}
}

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

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

[html] view plain
copy

<uses-permission android:name="android.permission.INTERNET" />

运行后效果:

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

正在等待云端数据,由于我这是2G的卡,等了好长时间还是加载不下来,等回公司了用公司的wifi试试,如果得到云端数据,就会通过Toast方式打印出来的。

抱歉!评论已关闭.