Android中主要通过RecognizerIntent来实现语音识别,其实代码比较简单,但是如果找不到设置,就会抛出异常 ActivityNotFoundException,所以我们需要捕捉这个异常。而且语音识别在模拟器上是无法测试的,因为语音识别是访问google 云端数据,所以如果手机的网络没有开启,就无法实现识别声音的!一定要开启手机的网络,如果手机不存在语音识别功能的话,也是无法启用识别!
下面是RecognizerIntentActivity中的代码:
01 |
public class RecognizerIntentActivity extends Activity { |
03 |
private Button btnReconizer; |
04 |
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234 ; |
06 |
protected void onCreate(Bundle savedInstanceState) { |
07 |
// TODO Auto-generated method stub |
08 |
super .onCreate(savedInstanceState); |
09 |
setContentView(R.layout.reconizer); |
11 |
btnReconizer=(Button) this .findViewById(R.id.btnRecognizer); |
12 |
btnReconizer.setOnClickListener( new OnClickListener() { |
15 |
public void onClick(View v) { |
16 |
// TODO Auto-generated method stub |
18 |
//通过Intent传递语音识别的模式,开启语音 |
19 |
Intent intent= new Intent
(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
|
21 |
intent.putExtra(
RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM
);
|
23 |
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "开始语音" ); |
25 |
startActivityForResult(
intent,
VOICE_RECOGNITION_REQUEST_CODE
);
|
26 |
} catch (Exception e) { |
27 |
// TODO: handle exception |
29 |
Toast.makeText(
getApplicationContext(),
"找不到语音设备" ,
1 ).show();
|
37 |
protected void onActivityResult(
int requestCode,
int resultCode,
Intent data) {
|
38 |
// TODO Auto-generated method stub |
40 |
if (requestCode==VOICE_RECOGNITION_REQUEST_CODE
&& resultCode==RESULT_OK){
|
42 |
ArrayList<String> results=data.getStringArrayListExtra
(RecognizerIntent.EXTRA_RESULTS);
|
44 |
String resultString= "" ; |
45 |
for ( int i= 0 ;i<results.size();i++){ |
46 |
resultString+=results.get(i); |
48 |
Toast.makeText( this , resultString, 1 ).show(); |
50 |
super .onActivityResult(requestCode, resultCode, data); |
<RESULTS.SIZE();I++){ pre="" }<="" data);="" resultcode,="" super.onactivityresult(requestcode,="" 1).show();="" resultstring,="" toast.maketext(this,="" }="" resultstring+="results.get(i);">
其主要原理就是将语音发送到google云端,然后云端处理,匹配相应的数据,发送到客户端。
最后不要忘记,在manifest中加入网络访问权限:
<uses-permission android:name="android.permission.INTERNET" />
运行后效果:
点击开始语音按钮,然后开始说话(这里要保证手机的网路是打开的):