3

我对文字转语音有一种奇怪的体验。

看我的代码:

Button b;
TextView title, body;
TextToSpeech tts;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.popups);
    b = (Button) findViewById(R.id.buttonok);
    title = (TextView) findViewById(R.id.textViewtitle);
    body = (TextView) findViewById(R.id.textViewbody);
    b.setText("ok");
    title.setText(Receive.address);
    body.setText(Receive.body);
    tts = new TextToSpeech(Popup.this, new TextToSpeech.OnInitListener() {

        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status != TextToSpeech.ERROR) {
                tts.setLanguage(Locale.US);
            }
        }
    });
            play();//this is not working??!!i don't know why
    b.performClick();//even this is not working
            /* but when i click this button it works??? how and why?*/
    b.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            play(); // Popup.this.finish();
        }
    });
}

private void play() {
    // TODO Auto-generated method stub
    tts.speak(Receive.body, TextToSpeech.QUEUE_FLUSH, null);

}

只有当我单击按钮时,我的文本到语音才能正常工作,但每当我不单击此按钮并在普通代码中编写 tts.speak() 时,它就无法正常工作......为什么?

问候查理

4

2 回答 2

4

您必须等待onInit被呼叫才能开始speak。在您的代码中,您在声明之后立即调用 play() 。onInit 是一个回调,它需要一些时间才能被调用。如果您在按钮出现后立即单击按钮,有时它会失败,因为尚未调用 onInit。您应该有一个类成员boolean mIsReady并在onInit 中将其设置为 true 。在你的play()方法 中

private void play() {
// TODO Auto-generated method stub
if (mIsReady) {
tts.speak(Receive.body, TextToSpeech.QUEUE_FLUSH, null);
}

}

于 2013-03-30T16:38:39.907 回答
2
b.performClick();//even this is not working
        /* but when i click this button it works??? how and why?*/
b.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        play(); // Popup.this.finish();
    }
});

You are performing a click with b.performClick() before setting its setOnClickListener. Also, you are better off making such calls on the onResume() method. OnCreate is meant to be used to bind views and prepare the activity. The onResume() method will be called before showing the view to the user on the foreground so that would be the best place to put this code.

Take a look at the activity lifecycle.

activity

于 2013-03-30T16:43:46.387 回答