简体   繁体   中英

Android static TextToSpeech

My problem is that I have an Android App which should tell the user something. I would like to have something like

Speaker.say("Hello World!");
// Wait till sentence is said
Speaker.say("Its " + time);
// Wait again
NextCommand.xyz();

I tried

import android.speech.tts.TextToSpeech;

public class TTS implements TextToSpeech.OnInitListener {
private static TextToSpeech mTts;
private String text;
private static final TTS helper = new TTS();

public static TTS getInstance(){

    return helper;
}


public void say(String text){
    if(mTts == null){
        this.text = text;
        mTts = new TextToSpeech(context /* ignore this please */, helper);
        mTts.setPitch(3);

    }
    else{
        mTts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }
}


@Override
public void onInit(int status) {
    if (status == TextToSpeech.SUCCESS) {
        mTts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }
}

public void stopTTS(){
    if(mTts != null){
        mTts.shutdown();
        mTts.stop();
        mTts = null;
    }
}

}

And then in onCreate:

TTS tts = TTS.getInstance();
tts.say("Hello World");
tts.say("Hello again!")

but: only first sentence is said and the optionsMenu is created after that

How to do this?

I solved it:

import android.speech.tts.TextToSpeech;

import java.util.Locale;

public class Test implements TextToSpeech.OnInitListener {
    TextToSpeech tts;
    String text;

    public Test(String text) {
        tts = new TextToSpeech(MyApplication.getContext(), this);
        this.text = text;
    }

    @Override
    public void onInit(int i) {
        if (i == TextToSpeech.SUCCESS) {
            tts.setLanguage(Locale.GERMAN);
            tts.setPitch(3);
            tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
            while(tts.isSpeaking());
        }
    }
}

and then you call it:

new Test("Hello");
new Test("Hello again!");
Toast.makeText(this, "Finished", Toast.LENGTH_LONG).show();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM