TTS doesn't speak from a service whereas it does it from an activity in android

萝らか妹 提交于 2019-12-03 04:07:11

I had the same problem and solved it this way: Instantiate TextToSpeech Object in a separate Class (in my case I furthermore use a Factory to check if the Android Version is at least Donut) and reuse it (see method init(Context context)). Please notice that the onInit(int status) is far from being ready to release.

Service:

@Override
public void onStart(Intent intent, int startId) {
Context context = getApplicationContext();
TtsProviderFactory ttsProviderImpl = TtsProviderFactory.getInstance();
if (ttsProviderImpl != null) {
    ttsProviderImpl.init(context);
    ttsProviderImpl.say("hope that helps);
}}

Factory:

public abstract class TtsProviderFactory {

public abstract void say(String sayThis);

public abstract void init(Context context);

public abstract void shutdown();


private static TtsProviderFactory sInstance;

public static TtsProviderFactory getInstance() {
    if (sInstance == null) {
        int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
        if (sdkVersion < Build.VERSION_CODES.DONUT) {
            return null;
        }

        try {
            String className = "TtsProviderImpl";
            Class<? extends TtsProviderFactory> clazz =
                    Class.forName(TtsProviderFactory.class.getPackage().getName() + "." + className)
                            .asSubclass(TtsProviderFactory.class);
            sInstance = clazz.newInstance();
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
    return sInstance;
}}

Implementation:

public class TtsProviderImpl extends TtsProviderFactory implements TextToSpeech.OnInitListener {

private TextToSpeech tts;

public void init(Context context) {
    if (tts == null) {
        tts = new TextToSpeech(context, this);
    }
}

@Override
public void say(String sayThis) {
    tts.speak(sayThis, TextToSpeech.QUEUE_FLUSH, null);
}

@Override
public void onInit(int status) {
    Locale loc = new Locale("de", "", "");
    if (tts.isLanguageAvailable(loc) >= TextToSpeech.LANG_AVAILABLE) {
        tts.setLanguage(loc);
    }
}

public void shutdown() {
    tts.shutdown();
}}

Did you installed the TTS engine in your device. I too faced the same problem with the same message. But later I found that I have to install the TTS engine to my real device also and it is available in the play store.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!