amanda45
amanda45

Reputation: 595

Android text to Speech

Im trying to use the TextToSpeech class to say text in my app. When I run my code I don't hear anything, the volume is high. What is wrong with my code? Do I need a permission or anything?

public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener  {

    TextToSpeech textToSpeech;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textToSpeech = new TextToSpeech(this, this);

        speakOut();
    }

    @Override
    public void onInit(int Text2SpeechCurrentStatus) {

        if (Text2SpeechCurrentStatus == TextToSpeech.SUCCESS) {

            int result = textToSpeech.setLanguage(Locale.US);

            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS", "This Language is not supported");
            } else {
                speakOut();
            }

        } else {
            Log.e("TTS", "Initilization Failed!");
        }
    }

    private void speakOut() {
        String g= "Hello";
        textToSpeech.speak(g, TextToSpeech.QUEUE_FLUSH, null);
    }
}

Upvotes: 1

Views: 1580

Answers (2)

CopsOnRoad
CopsOnRoad

Reputation: 267384

First and foremost thing : Check if any TTS engine is intalled in your device.

And no, you don't need any permission to use TTS.

Initialise TextToSpeech instance in the onCreate() method of the activity like this.

TextToSpeech t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
     @Override
     public void onInit(int status) {
        if(status != TextToSpeech.ERROR) {
           t1.setLanguage(Locale.UK);
        }
     }
  });

// This is your speakOut() method.

   private void speakOut() {
    String g= "Hello";
     t1.speak(g, TextToSpeech.QUEUE_FLUSH, null);
}

Hope it helps...

Upvotes: 1

Cesario
Cesario

Reputation: 75

This might be a comment, I am not sure but you can try change
if (Text2SpeechCurrentStatus == TextToSpeech.SUCCESS) {
into
if (Text2SpeechCurrentStatus != TextToSpeech.ERROR) {

And maybe you can debug, what is the value of Text2SpeechCurrentStatus

Upvotes: 0

Related Questions