Running Android TTS in a Service

前端 未结 3 473
轮回少年
轮回少年 2021-02-06 07:38

I\'m trying to get Android\'s TTS to run inside a service, but I have no idea why it isn\'t working, it compiles, doesn\'t crash, but it just doesn\'t work.

The Toast no

3条回答
  •  终归单人心
    2021-02-06 08:27

    You can do like below: It's working for me. You have to create an activity to start this service, like this: this.startService(intent)

    public class TTSService extends Service implements TextToSpeech.OnInitListener{
    
    private String str;
    private TextToSpeech mTts;
    private static final String TAG="TTSService";
    
    @Override
    
    public IBinder onBind(Intent arg0) {
    
        return null;
    }
    
    
    @Override
    public void onCreate() {
    
          mTts = new TextToSpeech(this,
                    this  // OnInitListener
                    );
          mTts.setSpeechRate(0.5f);
          Log.v(TAG, "oncreate_service");
         str ="turn left please ";
        super.onCreate();
    }
    
    
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
         if (mTts != null) {
                mTts.stop();
                mTts.shutdown();
            }
            super.onDestroy();
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
    
    
        sayHello(str);
    
        Log.v(TAG, "onstart_service");
        super.onStart(intent, startId);
    }
    
    @Override
    public void onInit(int status) {
        Log.v(TAG, "oninit");
         if (status == TextToSpeech.SUCCESS) {
                int result = mTts.setLanguage(Locale.US);
                if (result == TextToSpeech.LANG_MISSING_DATA ||
                    result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    Log.v(TAG, "Language is not available.");
                } else {
    
                    sayHello(str);
    
                }
            } else {
                Log.v(TAG, "Could not initialize TextToSpeech.");
            }
    }
    private void sayHello(String str) {
          mTts.speak(str,
                    TextToSpeech.QUEUE_FLUSH, 
                    null);
    }
    }
    

提交回复
热议问题