从OnStart调用TextToSpeech API时不起作用

时间:2011-06-02 03:37:18

标签: android text-to-speech

我在我的代码中使用TextToSpeech API,当我尝试从OnStart()调用.speak()函数时它不起作用,但是当我从onClickListener()按钮调用它时它可以正常工作。知道为什么吗?谢谢。

public class TtsDemoActivity extends Activity {

    private TextToSpeech mTts;
    private OnClickListener buttonListener = new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            PlaySound();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ttsdemo);

        // Initialize Text To speech
        mTts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {

            @Override
            public void onInit(int arg0) {
                // TODO Auto-generated method stub

            }
        });

        Button myButton = (Button)findViewById(R.id.buttontts1);
        myButton.setOnClickListener(buttonListener);
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        PlaySound();
    }

    protected void PlaySound()
    {
        String word = "Hello world";

        mTts.speak(word, TextToSpeech.QUEUE_FLUSH, null);

    }

2 个答案:

答案 0 :(得分:1)

您必须等到TTS子系统发出信号表明它已准备就绪:如果在调用onStart时它没有准备就绪,它将失败。如果您在准备就绪后立即发言,请在PlaySound内致电OnInitListener

@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ttsdemo);

        // Initialize Text To speech
        mTts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {

            @Override
            public void onInit(int arg0) {
if(arg0 == TextToSpeech.SUCCESS) PlaySound();

            }
        });

        Button myButton = (Button)findViewById(R.id.buttontts1);
        myButton.setOnClickListener(buttonListener);
    }

答案 1 :(得分:0)

也许我是盲人,但在你的onStart方法中,你并没有打电话

PlaySound()

就像你在

@Override public void onClick(View arg0) { PlaySound(); }