开发者

Android VoiceRecognition onActivityResult

开发者 https://www.devze.com 2023-04-12 13:45 出处:网络
we are trying to implement a simple quiz which should be controlled by VoiceRecognition. We have to Activities one QuestionActivity and one AnswerActivity. In the QuestionActivity the question is read

we are trying to implement a simple quiz which should be controlled by VoiceRecognition. We have to Activities one QuestionActivity and one AnswerActivity. In the QuestionActivity the question is read by TextToSpeech and afterwards the user can answer to the VoiceRecognition Activity. Then the AnswerActivity is started by startActivityForResult(...) which also uses a VoiceRecognition to make it possible for the user to navigate back to the next Question. However, if the user returns to his second Question, the VoiceRecognizer wouldnt work because of an unknown error. See the sample code below:

public class QuestionActivity extends Activity implements OnClickListener, OnInitListener, OnUtteranceCompletedListener {

private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;

private TxtToSpeech toSpeech =开发者_StackOverflow中文版 null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    toSpeech = new TxtToSpeech(this);
    setContentView(R.layout.main);

    // Get display items for later interaction
    Button speakButton = (Button) findViewById(R.id.btn_speak);

    // Check to see if a recognition activity is present
    PackageManager pm = getPackageManager();
    List<ResolveInfo> activities = pm.queryIntentActivities(
            new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
    if (activities.size() != 0) {
        speakButton.setOnClickListener(this);
    } else {
        speakButton.setEnabled(false);
        speakButton.setText("Recognizer not present");
    }
}

public void onClick(View v) {
    if (v.getId() == R.id.btn_speak) {
        startVoiceRecognitionActivity();
    }
}

private void startVoiceRecognitionActivity() {
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
    intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
    startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
        //---Code to restart
        //Without this code the recognizer wont work!
        Intent i = getIntent();
        finish();
        startActivity(i);
        //-----------------

        Intent intent = new Intent(this, SubActivity.class);
        startActivityForResult(intent , 2222);
    }
    else if( requestCode == 2222 )
    {
        saySomething();
    }

    super.onActivityResult(requestCode, resultCode, data);
}

void saySomething()
{
    toSpeech.playVoice(new String[] {"My Question"}, true); //true == start Recognition afterwards
}
@Override
public void onInit(int status) {
    toSpeech.mTts.setLanguage(Locale.US);
    toSpeech.mTts.setOnUtteranceCompletedListener(this);
    saySomething();
}

@Override
public void onUtteranceCompleted(String utteranceId) {
    startVoiceRecognitionActivity();
}

public class AnswerActivity extends Activity implements OnInitListener, OnUtteranceCompletedListener{

public final static int VOICE_RECOGNITION_REQUEST_CODE = 4321;
private TxtToSpeech toSpeech = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    toSpeech = new TxtToSpeech(this);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        setResult(RESULT_OK);
        finish();

    super.onActivityResult(requestCode, resultCode, data);
}

@Override
public void onUtteranceCompleted(String utteranceId) {
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
    startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}

@Override
public void onInit(int status) {
    toSpeech.mTts.setOnUtteranceCompletedListener(this);
    toSpeech.mTts.setLanguage(Locale.US);
    toSpeech.playVoice(new String[] {"correct answer"}, true); //again start recognition after voice
}   

}

public class TxtToSpeech {
   public TextToSpeech      mTts            = null;
   public Context       ctxt            = null;
   public boolean       recordAnswer    = false;

    public TxtToSpeech(Context context){

        mTts = new TextToSpeech(context, (OnInitListener)context);
        ctxt = context; 
    }       
    public void playVoice(String[] sentences, boolean answer){
        final HashMap<String, String> utteranceMap = new HashMap<String,String>();
        utteranceMap.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "1");

        recordAnswer = answer;

        StringBuilder builder = new StringBuilder();
        for( String s:sentences)
        {
            builder.append(s);
            builder.append(",");
        }
        final String text = builder.toString();

        if( recordAnswer )
            mTts.speak(text, TextToSpeech.QUEUE_ADD, utteranceMap);
        else
            mTts.speak(text, TextToSpeech.QUEUE_ADD, null);
    }

}

do I always have to restart the whole QuestionActivity in order to have a running VoiceRecognition? During the game the user only cycles between the Question- and the AnswerActivity is there a nicer way than just finish()-ing the Activities?


Please describe the error you get.

In general, restarting an activity should be a normal part of any Android activity since the user switches all the time. Also, if two activities are awkward, maybe you can get by with just a single one.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号