开发者

TextToSpeech API doesn't work when its called from OnStart

I'm using the TextToSpeech API in my code and it doesn't work when I try to call .speak() function from OnStart(), however it works when I call it from a button onClickListener(). Any idea why? Thank you.

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

    }


You must wait until the TTS subsystem signals that it is ready: if it isn't ready when onStart is called, it will fail. If you are trying to speak as soon as it is ready call PlaySound from inside the 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);
    }


Maybe I am blind, but in your onStart method, you aren't ever calling

PlaySound()

Like you are in

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜