歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android語音識別技術

Android語音識別技術

日期:2017/3/1 10:33:10   编辑:Linux編程

今天從網上找了個例子實現了語音識別,個人感覺挺好玩的,就把代碼貼出來與大家分享下:

Android中主要通過RecognizerIntent來實現語音識別,其實代碼比較簡單,但是如果找不到設置,就會拋出異常ActivityNotFoundException,所以我們需要捕捉這個異常。而且語音識別在模擬器上是無法測試的,因為語音識別是訪問google雲端數據,所以如果手機的網絡沒有開啟,就無法實現識別聲音的!一定要開啟手機的網絡,如果手機不存在語音識別功能的話,也是無法啟用識別!

下面是RecognizerIntentActivity中的代碼:

  1. public class RecognizerIntentActivity extends Activity {
  2. private Button btnReconizer;
  3. private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
  4. @Override
  5. protected void onCreate(Bundle savedInstanceState) {
  6. // TODO Auto-generated method stub
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.reconizer);
  9. btnReconizer=(Button) this.findViewById(R.id.btnRecognizer);
  10. btnReconizer.setOnClickListener(new OnClickListener() {
  11. @Override
  12. public void onClick(View v) {
  13. // TODO Auto-generated method stub
  14. try{
  15. //通過Intent傳遞語音識別的模式,開啟語音
  16. Intent intent=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
  17. //語言模式和自由模式的語音識別
  18. intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
  19. //提示語音開始
  20. intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "開始語音");
  21. //開始語音識別
  22. startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
  23. }catch (Exception e) {
  24. // TODO: handle exception
  25. e.printStackTrace();
  26. Toast.makeText(getApplicationContext(), "找不到語音設備", 1).show();
  27. }
  28. }
  29. });
  30. }
  31. @Override
  32. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  33. // TODO Auto-generated method stub
  34. //回調獲取從谷歌得到的數據
  35. if(requestCode==VOICE_RECOGNITION_REQUEST_CODE && resultCode==RESULT_OK){
  36. //取得語音的字符
  37. ArrayList<String> results=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
  38. String resultString="";
  39. for(int i=0;i<results.size();i++){
  40. resultString+=results.get(i);
  41. }
  42. Toast.makeText(this, resultString, 1).show();
  43. }
  44. super.onActivityResult(requestCode, resultCode, data);
  45. }
  46. }
Copyright © Linux教程網 All Rights Reserved