Search code examples
androidservicebroadcastreceivertext-to-speech

TTS inside Service


I am working on announcer project. My TTS service doesn't speak inside service. My logcat says that it runs it but can't speak it. here is my code. plz tell me what's going wrong? I am calling it from broadcastreciever.

public class Speaker extends Service implements TextToSpeech.OnInitListener {
    public static TextToSpeech mtts;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onCreate() {
        Log.d("SpeakerService", "Service created successfully!");
        mtts = new TextToSpeech(getApplicationContext(), this);
        mtts.setLanguage(Locale.ENGLISH);

    }

    @Override
    public void onStart(Intent intent, int startid) {
        Log.d("SpeakerService", "Service started successfully!");
        Log.d("SpeakerService", "Service started successfully!");
        // Log.d("SpeakerService", "tspker.mtts = " +
        // TextSpeaker.mtts.toString());
        mtts = new TextToSpeech(getApplicationContext(), this);
        mtts.setLanguage(Locale.ENGLISH);
        mtts.speak("The service has been done The service has been done",
                TextToSpeech.QUEUE_FLUSH, null);
        Toast.makeText(getApplicationContext(),
                "The service has been done!", Toast.LENGTH_SHORT)
                .show();
    }

    @Override
    public void onDestroy() {
        if (mtts != null) {
            mtts.stop();
            Toast.makeText(getApplicationContext(),
                    "The service has been destroyed!", Toast.LENGTH_SHORT)
                    .show();
        }

    }

    @Override
    public void onInit(int arg0) {

    }

}

Solution

  • You have to call speak in onInit or after onInit is called.