java如何从另一个活动调用TextToSpeech活动?
我有一个活动(MainActivity
),它实现了TextToSpeech
并且工作得很好。当一个按钮的onClick
被调用时,它会说出在EditText
中键入的任何内容
主要活动:
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener{
private TextToSpeech engine;
private EditText text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (EditText) findViewById(R.id.text);
engine = new TextToSpeech(this, this);
Intent i=getIntent();
Bundle b=i.getExtras();
word=b.getString("word");
speakText2(word);
}
// speakText is called by onClick button
public void speakText(View v) {
String textContents = text.getText().toString();
engine.speak(textContents, TextToSpeech.QUEUE_FLUSH, null, null);
}
public void speakText2(String textContents) {
engine.speak(textContents, TextToSpeech.QUEUE_ADD, null, null);
}
@Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS) {
//Setting speech Language
engine.setLanguage(Locale.ENGLISH);
engine.setPitch(1);
}
}
}
现在,我想从另一个活动调用MainActivity
,并传递一个字符串来大声说话。
我试过:
MainActivity mainactivity = new MainActivity();
String word;
word = "speak";
mainactivity.speakText2(word); // Error
但是,得到错误:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int 安卓.speech.tts.TextToSpeech.speak(java.lang.CharSequence, int, 安卓.os.Bundle, java.lang.String)' on a null object reference
at MainActivity.speakText2(TTSEngine.java:53)
我尝试使用其他活动的意图:
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("word", word);
startActivity(intent);
但是,得到错误:
I/TextToSpeech: Sucessfully bound to com.google.安卓.tts
W/TextToSpeech: speak failed: not bound to TTS engine
W/TextToSpeech: speak failed: not bound to TTS engine
W/TextToSpeech: speak failed: not bound to TTS engine
I/TextToSpeech: Connected to ComponentInfo{com.google.安卓.tts/com.google.安卓.tts.service.GoogleTTSService}
I/TextToSpeech: Set up connection to ComponentInfo{com.google.安卓.tts/com.google.安卓.tts.service.GoogleTTSService}
我试图在我想使用它的活动中实现TextToSpeech
。但是,这不是我第一次打电话给speakText2并给出错误:
W/TextToSpeech: speak failed: not bound to TTS engine
I/TextToSpeech: Connected to ComponentInfo{com.google.安卓.tts/com.google.安卓.tts.service.GoogleTTSService}
I/TextToSpeech: Set up connection to ComponentInfo{com.google.安卓.tts/com.google.安卓.tts.service.GoogleTTSService}
在剩下的时间里,它工作得很好。知道怎么解决吗
# 1 楼答案
在onInit完成后,您只能让引擎说话,在onInit()中也可以这样做:
if(status==TextToSpeech.SUCCESS){ speakText2(word)
}