2013-04-21 75 views
1

我使用OnUtteranceCompletedListener來檢測TTS何時完成發言,但是OnUttereanceCompleted永遠不會被調用。監聽器是在HashMap之前的onInit中創建的,所以我不知道什麼是錯的。任何想法?TextToSpeech OnUtteranceCompletedListener不能正常工作

public class TTSActivity extends Activity implements TextToSpeech.OnInitListener, OnUtteranceCompletedListener 
{ 
    private TextToSpeech tts; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.tts_layout); 

     tts = new TextToSpeech(this, this); 
    } 



    @Override 
    public void onDestroy() { 
     // Don't forget to shutdown tts! 
     if (tts != null) { 
      tts.stop(); 
      tts.shutdown(); 
     } 
     super.onDestroy(); 
    } 

    @Override 
    public void onInit(int status) 
    { 
     if (status == TextToSpeech.SUCCESS) 
     { 
      tts.setOnUtteranceCompletedListener(this); 
      int result = tts.setLanguage(Locale.US); 

      if (result == TextToSpeech.LANG_MISSING_DATA 
        || result == TextToSpeech.LANG_NOT_SUPPORTED) { 
       Log.e("TTS", "This Language is not supported"); 
      } else { 
       speakOut(); 
      } 
     } else { 
      Log.e("TTS", "Initilization Failed!"); 
     } 

    } 

    private void speakOut() 
    { 
     HashMap<String, String> myHashAlarm = new HashMap<String, String>(); 
     myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_ALARM)); 
     myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "FINISHED PLAYING"); 
    tts.speak("Some text.", TextToSpeech.QUEUE_FLUSH, myHashAlarm); 
    } 

    @Override 
    public void onUtteranceCompleted(String utteranceId) 
    { 
     if(utteranceId=="FINISHED PLAYING") 
     { 
      Log.i("TTS", "Called"); //never called 
     } 
    } 

回答

2

得到它的工作。問題在於字符串的比較。 線:

if(utteranceId=="FINISHED PLAYING") 

必須改爲:

if(utteranceId.equals("FINISHED PLAYING"))