Android:SpeechRecognition无效

时间:2016-07-27 20:30:11

标签: android speech-recognition

我正在我的应用程序中进行语音识别,我有2个命令命令A和命令B,假设我点击麦克风并说出命令A它必须启动活动A或活动B是命令。 在下面的代码中START_ACTIVITY1是我的命令A

protected static final int RESULT_SPEECH_START_ACTIVITYA=1;
protected static final int RESULT_SPEECH_START_ACTIVITYB=2;


  mic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mic.setBackgroundResource(R.drawable.micactive);
                Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");

                try {
                    startActivityForResult(intent, RESULT_SPEECH_START_ACTIVITYA);

//                    manInactiveButton.setBackgroundResource(R.drawable.man_inactive);
                } catch (ActivityNotFoundException e) {
                    Toast t = Toast.makeText(getApplicationContext(), "Oops, Your device doesn't support Speech to Text", Toast.LENGTH_LONG);
                    t.show();

                }

            }
        });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case RESULT_SPEECH_START_ACTIVITYA:{
                if (resultCode == RESULT_SPEECH_START_ACTIVITYA && null != data) {
                    ArrayList<String> text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    Intent mainIntent= new Intent(First_Screen.this, Second.class);
                    startActivity(mainIntent);
                }
            }



        }
    }

1 个答案:

答案 0 :(得分:0)

public class VoiceRecognition implements RecognitionListener, Runnable 
{
    @Override
    public void run()
    {
        recognizer = SpeechRecognizer.createSpeechRecognizer(yourContext);
        recognizer.setRecognitionListener((RecognitionListener) this);

         intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
         //... all the intent stuff ...
         intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
         recognizer.startListening(intent);
    }
    @Override
    public void onResults(Bundle results)
    {
       ArrayList<String> matches;
       matches=results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
    }
 }

....
VoiceRecognition voiceRecognizer = new VoiceRecognition();
Handler loopHandler = new Handler(Looper.getMainLooper());
loopHandler.post(voiceRecognizer);
相关问题