Search code examples
androidspeech-recognitiontext-to-speech

Why is it not sleeping for 3 seconds before it starts listening?


I'm trying to do:

  1. perform a TextToSpeech
  2. SpeechRecognizer starts listening as the user repeats the TextToSpeech'd word/phrases

But my problem is that, for example, if i were to say "example" via TextToSpeech, when the SpeechRecognizer starts listening, it also takes in the "example" from previous and adds onto the one that the user says. So at the end, i ended up "example example", which i didn't want.

Code:

public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    // TODO Auto-generated method stub
    item = (String) parent.getItemAtPosition(position); 
    tts.speak(item, TextToSpeech.QUEUE_FLUSH, null);
    Thread thread = new Thread() {
        public void run() {
            try {
                sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    thread.start();
    sr.startListening(srIntent);
}

Solution

  • You are doing two process in Two thread. You are creating Thread One and make it sleep for 3 seconds and sr.startListening(srIntent); start Intent in separate UI Thread. So it start Intent Immediately. Use both process in one Thread like i post it below

    public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    // TODO Auto-generated method stub
    item = (String) parent.getItemAtPosition(position); 
    tts.speak(item, TextToSpeech.QUEUE_FLUSH, null);
    Thread thread = new Thread() {
        public void run() {
            try {
                sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        mSpeech.sendEmptyMessage(0);
        }
    };
    thread.start();
    

    }

    Create one Inner Handler class to perform UI operations

    private Handler mSpeech=new Handler(){
        public void handleMessage(android.os.Message msg) {
             sr.startListening(srIntent);
        }
    };