--首先先確認使用者有沒有裝語音辨識,沒有的話幫他導向Market下載--

PackageManager pm=getPackageManager();

//---------查詢有無裝Google Voice Search Engine---------
List<ResolveInfo> activities=pm.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH),0);
//-------------如果有找到-------------
if(activities.size()!=0){
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_MAX_RESULTS,1);//設定只出現辨識結果第一筆

//----------開啟語音辨識Intent-----------
startActivityForResult(intent,VOICE_RECOGNITION_REQUEST_CODE);//VOICE_RECOGNITION_REQUEST_CODE是自訂 因為當結果回傳時要告訴她是誰呼叫他

}catch(Exception e){//catch error message
new AlertDialog.Builder(mainActivity.this)
.setTitle("Error")
.setMessage(e.getMessage()).show();;
}
}else{//----------如果找不到-------------

//利用Toast告訴User找不到Google語音
Toast.makeText
(
mainActivity.this,
"找不到Google語音 即將幫你導向下載頁面",
Toast.LENGTH_LONG
).show();
//且導向Market Google語音下載網頁 讓使用者下載
String url="https://market.android.com/details?id=com.google.android.voicesearch";
Intent ie = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
//啟動Intent
startActivity(ie);

}

----onActivityResult----

//onActivityResult===========================================================
public void onActivityResult(int requestCode, int resultCode, Intent data) {

switch (requestCode) {

case VOICE_RECOGNITION_REQUEST_CODE://語音結果回傳
   if(requestCode==VOICE_RECOGNITION_REQUEST_CODE
   &&resultCode==RESULT_OK){
    //---------取得辨識結果----------------------
    ArrayList<String> voiceResults=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
    if(voiceResults.size()>0){//如果辨識結果>0
           //就可以把辨識結果voiceResults拿來用了
    }else{//辨識結果<=0表示無法辨識
    Toast.makeText(mainActivity.this,"無法辨識",Toast.LENGTH_SHORT).show();
    }
  }
break;
}
}


, , , ,
創作者介紹

Mazs's Notes

cookiesp 發表在 痞客邦 PIXNET 留言(0) 人氣()