2013-07-31 27 views
2

我想要做的事:为什么它在开始收听之前不睡3秒钟?

  1. 执行TextToSpeech
  2. SpeechRecognizer开始监听作为用户重复 TextToSpeech'd词/短语

但我的问题是,例如,如果我通过TextToSpeech说“example”,那么当SpeechRecognizer开始收听时,它也会从之前的“示例”中获取并添加到用户所说的“示例”中。最后,我结束了“示例”,这是我不想要的。

代码:

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); 
} 
+3

,因为你的睡眠是把外面的睡眠与另一个线程 – njzk2

+0

线程对象 –

+0

@ njzk2是的正确 – Sameer

回答

2

你正在做的两种工艺在两个线程中。您正在创建线程并使其在3秒内休眠,并在独立的UI线程中启动sr.startListening(srIntent); Intent。所以它马上启动Intent。同时使用过程中的一个线程像我张贴下面

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(); 

}

创建一个内部处理程序类来执行UI操作

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

是的!此解决方案工作。但是,你介意给我解释处理程序的用法吗?我从来没有遇到过这个词,因为我只是一个初学者。非常感激! – rx24race

+0

阅读此文档http://developer.android.com/reference/android/os/Handler.html – Sameer

+0

感谢您的时间和帮助! – rx24race

0

它必须是run()

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(); 
      } 
      sr.startListening(srIntent); 
     } 
    }; 
    thread.start(); 

} 
+0

我试过这种方式,并在等待3秒后自动崩溃。 – rx24race

+0

它说:SpeechRecognizer应该只用于应用程序的主线程 – rx24race

+0

@ rx24race试试我的解决方案,你必须带着处理器开始语音识别 – Sameer

相关问题