今天從網上找了個例子實現了語音識別,個人感覺挺好玩的,就把代碼貼出來與大家分享下:
Android中主要通過RecognizerIntent來實現語音識別,其實代碼比較簡單,但是如果找不到設置,就會拋出異常ActivityNotFoundException,所以我們需要捕捉這個異常。而且語音識別在模擬器上是無法測試的,因為語音識別是訪問google雲端數據,所以如果手機的網絡沒有開啟,就無法實現識別聲音的!一定要開啟手機的網絡,如果手機不存在語音識別功能的話,也是無法啟用識別!
下面是RecognizerIntentActivity中的代碼:
- 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);
- }
- }