Milan Vukovic
Milan Vukovic

Reputation: 11

Why does TextToSpeech fail to initialize in this class?

I have a class which is supposed to speak the description of a given entry from glossary. The code is like this:

package college.projects.glossary;

import android.content.Intent;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;

import java.util.Locale;

public class GlossaryEntryPlayer extends Object implements IGlossaryEntryPlayer, TextToSpeech.OnInitListener {

    protected MyActivity activity_;

    private TextToSpeech textToSpeech_ = null;

    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            int result = textToSpeech_.setLanguage(Locale.US);
            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                MyUtils.UIDebug(this.activity_.getApplicationContext(), "Language support is bad");
            } else {
                MyUtils.UIDebug(this.activity_.getApplicationContext(), "Language support is OK");
            }
        } else {
            MyUtils.UIDebug(this.activity_.getApplicationContext(), "TextToSpeech is bad");
        }
    }

    public GlossaryEntryPlayer(MyActivity activity) {
        super();
        this.activity_ = activity;
        textToSpeech_ = new TextToSpeech(this.activity_, this);
    }

    @Override
    public boolean play(GlossaryEntry entry) {
        if (null != entry) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                textToSpeech_.speak(entry.getDescription(), TextToSpeech.QUEUE_FLUSH, null, null);
                return true;
            } else {
                MyUtils.UIDebug(this.activity_.getApplicationContext(), "Version is bad");
                return false;
            }
        } else {
            return false;
        }
    }

}

The problem is in onInit() since I always get the message "TextToSpeech is bad". What's wrong with this class? Android emulator used is 5.1 WVGA API 30, RAM 512 MB, the default language is US-ENG. The laptop on which Android Studio runs is Lenovo AMD A4-G50, 4GB Ram, 1.8Ghz

Upvotes: 1

Views: 1401

Answers (1)

Mohit Singh
Mohit Singh

Reputation: 1450

According to Google, "Apps targeting Android 11 that use text-to-speech should declare TextToSpeech.Engine#INTENT_ACTION_TTS_SERVICE in the queries elements of their manifest:"

So, add this to your AndroidManifest.xml:

<queries>
    <intent>
        <action android:name="android.intent.action.TTS_SERVICE" />
    </intent>
</queries>

Adding this before <application tag worked for me. (Android Studio says Element queries is not allowed here though).

Upvotes: 3

Related Questions