5

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

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()onCreateor中运行onStart()

4

3 回答 3

4

你可以这样做:

@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.");
    }

}

这不是很好,但它有效。我希望有人会找到更好的解决方案...

于 2013-01-30T19:09:08.477 回答
2

请看一下本教程
基本上,它在方法期间强制初始化onCreate()

// Fire off an intent to check if a TTS engine is installed
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);

然后,您将能够在开始时说出您想要的任何文本(无需用户进行任何交互)。当然,说话会起作用。


弥尔顿

于 2014-05-21T14:50:34.910 回答
0

尝试为使用给定 TTS 引擎的 TextToSpeech 类使用另一个构造函数:

TextToSpeech(this,this,"com.google.android.tts");

代替:

new TextToSpeech(this, this);
于 2017-01-08T18:28:34.717 回答