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" />
運行後效果:
點擊開始語音按鈕,然後開始說話(這裏要保證手機的網路是打開的):