文本到语音自动播放
问题描述:
我在我的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);
}
}
答
之所以出现这种情况是因为你调用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();
}
答
我的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();
}
我刚刚意识到对不起 – JamesCgrave 2014-12-04 15:14:45
没问题。它发生了:) – 2014-12-04 15:18:17
任何机会,你会有一个孤立我的问题在选项卡上? :) – JamesCgrave 2014-12-04 15:19:34