TextToSpeech API doesn't work when its called

2019-08-27 10:48发布

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

    }

2条回答
女痞
2楼-- · 2019-08-27 11:09

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);
    }
查看更多
爷、活的狠高调
3楼-- · 2019-08-27 11:18

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

查看更多
登录 后发表回答