TTS和播放声音 - Android

时间:2013-05-12 17:50:01

标签: android android-viewpager text-to-speech

我的应用程序中有一个viewpager。当用户向右/向左滑动时,我使用TTS引擎说出文本,使用MediaPlayer播放声音。

问题是同时播放..一旦TTS引擎说文字结束,我怎么播放声音?

P.S:我不想睡觉或等待。

更新

这是我的代码:

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
@Override
public void onInit(int status) {
    if (status == TextToSpeech.SUCCESS) {

        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
        } else {
            //Do Something here
        }


        if(Build.VERSION.SDK_INT  >= 15 ){
            UtteranceProgressListener listener = new UtteranceProgressListener() {

                @Override
                public void onStart(String utteranceId) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onError(String utteranceId) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onDone(String utteranceId) {
                    // TODO Auto-generated method stub
                    //start MediaPlayer
                    playMedia(viewPager.getCurrentItem());
                }
            };
            tts.setOnUtteranceProgressListener(listener);
        }
        else{
            tts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener(){

                @Override
                public void onUtteranceCompleted(String arg0) {
                     playMedia(viewPager.getCurrentItem());
                }

              });
        }
    } else {
        Intent installIntent = new Intent();
        installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
        startActivity(installIntent);
    }
}

2 个答案:

答案 0 :(得分:6)

你必须给它一个id参数。否则它不会调用侦听器:

HashMap<String, String> params = new HashMap<String, String>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"stringId");

textToSpeech.speak(string,TextToSpeech.QUEUE_ADD, params);

答案 1 :(得分:2)

在Android中他们有两个 API 来检测 TTS 引擎是否完成了发言:

  • <强>&GT; Android 4(ICS)

    UtteranceProgressListener listener = new UtteranceProgressListener() {
    
        @Override
        public void onStart(String utteranceId) {
            // TODO Auto-generated method stub
    
        }
    
        @Override
        public void onError(String utteranceId) {
            // TODO Auto-generated method stub
    
        }
    
        @Override
        public void onDone(String utteranceId) {
            // TODO Auto-generated method stub
            //start MediaPlayer
        }
    };
        yourTTSObject.setOnUtteranceProgressListener(listener);
    
  • Perior to ICS Android 4.0 您可以使用:

    yourTTSObject.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener(){
    
        @Override
        public void onUtteranceCompleted(String arg0) {
              // start your mediaplayer here
        }
    
      });
    

    查看文档here