我是否在Android上正确使用Text To Speech TTS

时间:2014-12-17 09:38:23

标签: java android text-to-speech

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences gameSettings = getSharedPreferences("LangPreferences",0); 
        String lang=gameSettings.getString("Lang", "");
        System.out.println("@@menu"+lang);

            setContentView(R.layout.alarm);
          toSpeak="Alarm Received weak up";
        Toast.makeText(this, "Alarm Recieved", Toast.LENGTH_LONG).show();
        ttobj=new TextToSpeech(Alarm.this, 
              new TextToSpeech.OnInitListener() {
              @Override
              public void onInit(int status) {
                 if(status != TextToSpeech.ERROR){
                     ttobj.setLanguage(Locale.UK);
                    }               
                 }
              });
        //String toSpeak = write.getText().toString();
         speak();

    }
     @Override
       public void onPause(){
          if(ttobj !=null){
             ttobj.stop();
             ttobj.shutdown();
          }
          super.onPause();
       }
     public void speak()
     {
         Toast.makeText(getApplicationContext(), toSpeak, 
                  Toast.LENGTH_SHORT).show();
               try{   ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
               }
               catch(Exception e)
               {

               }
     }

我在说闹钟应用程序。我在警报类中写了TTS它显示警报和Toast消息我给TTS引擎但是TTS引擎没有说话

它显示的logcat框

12-17 15:00:01.264: W/TextToSpeech(31970): speak failed: not bound to TTS engine

1 个答案:

答案 0 :(得分:0)

你只能在调用onInit()之后调用speak()。所以你可以在onInit()中调用speak方法。下面我修改你的onInit()方法。

       @Override
        public void onInit(int status) {
            if (status != TextToSpeech.ERROR) {
                ttobj.setLanguage(Locale.US); //here u have to set your local language
            }
            if(status==TextToSpeech.SUCCESS){
                speak(); 
            }
        }