我遵循了一些教程,但是遇到了同样的问题。首先,这是我的简单代码:

import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;

public class AchievementsActivity extends Activity implements OnInitListener {

    TextToSpeech reader;
    Locale canada;
    boolean readerInit = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


        canada = Locale.ENGLISH;
        reader = new TextToSpeech(this, this);

        //speak();

        //      while (reader.isSpeaking()) {} //waiting for reader to finish speaking

    }

    @Override
    public void onStart()   {
        super.onStart();
        //speak();

    }

    @Override
    public void onInit(int status) {

        if (status == TextToSpeech.SUCCESS) {
            reader.setLanguage(canada);
            reader.setPitch(0.9f);
            Log.e("Init", "Success");
            readerInit = true;
            speak();
        }

        else
            System.out.println("Something went wrong.");
    }

    public void speak() {
        reader.speak("You currently have no achievements.", TextToSpeech.QUEUE_FLUSH, null);
    }
}

现在,请注意我已注释掉的onCreate()中的第一个语音,也已我注释掉的onStart()中的第二个语音。根据我在LogCat中收到的信息,这样做的原因很明显。由于某种原因,它们在reader的初始化完成之前被调用。因此,我拥有此工作权利的唯一方法是,在确保确定要在其自身的方法内完成初始化之后,立即放置speak()函数。

所以我想知道是否有什么方法可以等待初始化完成,然后在speak()onCreate中运行onStart()

最佳答案

您可以执行以下操作:

@Override
public void onInit(int status) {

    if (status == TextToSpeech.SUCCESS) {
        reader.setLanguage(canada);
        reader.setPitch(0.9f);
        Log.e("Init", "Success");
        readerInit = true;

        // wait a little for the initialization to complete
        Handler h = new Handler();
        h.postDelayed(new Runnable() {
            @Override
            public void run() {
                // run your code here
                speak();
            }
        }, 400);

    }

    else {
        System.out.println("Something went wrong.");
    }

}

它不是很好,但是可以。我希望有人能找到更好的解决方案...

关于android - 文字转语音无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14563098/

10-13 09:26