2011-06-02 19 views
0

我在我的代碼中使用TextToSpeech API,當我嘗試從OnStart()調用.speak()函數時它不起作用,但它在我從onClickListener()按鈕調用它。任何想法爲什麼?謝謝。TextToSpeech API在從OnStart調用時不起作用

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

    } 

回答

1

您必須等到TTS子系統的信號,這是準備:如果在onStart被稱爲是沒有準備好,它就會失敗。如果你想盡快它準備調用PlaySoundOnInitListener裏面講:

@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); 
    } 
+0

謝謝。那樣做了。 – atbebtg 2011-06-02 04:14:16

0

也許我是個盲人,但在你的OnStart方法,你是不是曾經呼籲

PlaySound() 

像你在

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

+0

我確實叫它。你錯過了。但它很酷:) – atbebtg 2011-06-02 04:14:00