我有个活动(
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 = new MainActivity();
String word;
word = "speak";
mainactivity.speakText2(word); // Error
但是,获取错误:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.speech.tts.TextToSpeech.speak(java.lang.CharSequence, int, android.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.android.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.android.tts/com.google.android.tts.service.GoogleTTSService}
I/TextToSpeech: Set up connection to ComponentInfo{com.google.android.tts/com.google.android.tts.service.GoogleTTSService}
文本语音
W/TextToSpeech: speak failed: not bound to TTS engine
I/TextToSpeech: Connected to ComponentInfo{com.google.android.tts/com.google.android.tts.service.GoogleTTSService}
I/TextToSpeech: Set up connection to ComponentInfo{com.google.android.tts/com.google.android.tts.service.GoogleTTSService}
在剩下的时间里,它工作得很好。知道怎么解决吗?