Android静态TextToSpeech

时间:2014-09-14 14:09:47

标签: java android static text-to-speech

我的问题是我有一个Android应用程序应该告诉用户一些东西。我想要像

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

我试过

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;
    }
}

}

然后在onCreate:

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

但: 只说第一句话,然后在那之后创建optionsMenu

怎么做?

1 个答案:

答案 0 :(得分:1)

我解决了它:

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());
        }
    }
}

然后你称之为:

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