TextToSpeech OnUtteranceCompletedListener无法正常工作

时间:2013-04-21 11:26:37

标签: android

我正在使用OnUtteranceCompletedListener来检测TTS何时结束讲话,但是从不调用OnUttereanceCompleted。监听器是在onInit中创建的,在HashMap之前,所以我不知道出了什么问题。有什么想法吗?

    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
        }   
    }

1 个答案:

答案 0 :(得分:3)

搞定了。问题在于字符串的比较。 这一行:

if(utteranceId=="FINISHED PLAYING")

必须更改为:

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