2014-12-04 73 views
0

我在我的android應用程序中有一個文本到語音功能,可以用於onClick事件,當活動開始時,文本到語音的啓動沒有單擊按鈕就會出現問題,是否有一行我可以通過代碼來阻止這種情況發生,謝謝。文本到語音自動播放

package com.androidhive.texttospeech; 

import java.util.Locale; 

import android.app.Activity; 
import android.os.Bundle; 
import android.speech.tts.TextToSpeech; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 

public class AndroidTextToSpeechActivity extends Activity implements 
    TextToSpeech.OnInitListener { 
/** Called when the activity is first created. */ 

    private TextToSpeech tts; 
    private Button button1; 
    private TextView txtText; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    tts = new TextToSpeech(this, this); 

    button1 = (Button) findViewById(R.id.button1); 

    txtText = (TextView) findViewById(R.id.txtText); 

    // button on click event 
    button1.setOnClickListener(new View.OnClickListener() { 

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

    }); 
} 

@Override 
public void onDestroy() { 
    // Don't forget to shutdown! 
    if (tts != null) { 
     tts.stop(); 
     tts.shutdown(); 
    } 
    super.onDestroy(); 
} 

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

    if (status == TextToSpeech.SUCCESS) { 

     int result = tts.setLanguage(Locale.US); 

     // tts.setPitch(5); // set pitch level 

     // tts.setSpeechRate(2); // set speech speed rate 

     if (result == TextToSpeech.LANG_MISSING_DATA 
       || result == TextToSpeech.LANG_NOT_SUPPORTED) { 
      Log.e("TTS", "Language is not supported"); 
     } else { 
      button1.setEnabled(true); 
      speakOut(); 
     } 

    } else { 
     Log.e("TTS", "Initilization Failed"); 
    } 

    } 

private void speakOut() { 

    String text = txtText.getText().toString(); 

    tts.speak(text, TextToSpeech.QUEUE_FLUSH, null); 
    } 
} 

回答

0

之所以出現這種情況是因爲你調用SPEAKOUT#在OnInit()方法,去除SPEAKOUT():

if (result == TextToSpeech.LANG_MISSING_DATA 
       || result == TextToSpeech.LANG_NOT_SUPPORTED) { 
      Log.e("TTS", "Language is not supported"); 
     } else { 
      button1.setEnabled(true); 
      // speakOut(); 
     } 
+0

我剛剛意識到對不起 – JamesCgrave 2014-12-04 15:14:45

+0

沒問題。它發生了:) – 2014-12-04 15:18:17

+0

任何機會,你會有一個孤立我的問題在選項卡上? :) – JamesCgrave 2014-12-04 15:19:34

0

我的OnInit()後,TextToSpeech被實例化和初始化成功後,將其稱之爲看到了這些代碼。看到speakOut()在這裏?這就是導致你的問題的原因。

if (result == TextToSpeech.LANG_MISSING_DATA 
      || result == TextToSpeech.LANG_NOT_SUPPORTED) { 
     Log.e("TTS", "Language is not supported"); 
} else { 
    button1.setEnabled(true); 
    speakOut(); 
}