ive观看了教程并精确地复制了,但文本会引发错误。这是代码:
public void speak(String text){
TextToSpeech text_to_speech;
text_to_speech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS){
int result = text_to_speech.setLanguage(Locale.ENGLISH);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
Log.e("TTS", "Language not supported");
} else {
text_to_speech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
} else {
Log.e("TTS", "Failed");
}
}
});
}
错误是"可能不会初始化的变量text_to_to_speech"。
更新:错误仅指向int result = text_to_speech.setLanguage(Locale.ENGLISH);
您可以通过这样做来解决即时问题:
public class MainActivity extends AppCompatActivity {
TextToSpeech text_to_speech; // declare tts here
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
speak("hello");
}
public void speak(final String text){ // make text 'final'
// ... do not declare tts here
text_to_speech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS){
int result = text_to_speech.setLanguage(Locale.ENGLISH);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
Log.e("TTS", "Language not supported");
} else {
text_to_speech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
} else {
Log.e("TTS", "Failed");
}
}
});
}
}
我建议以这种方式设置东西:
public class MainActivity extends AppCompatActivity {
// declare the tts here so it can be accesed from all functions
TextToSpeech text_to_speech;
// track whether the tts is initialized
boolean ttsIsInitialized = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initilize the tts here once, (not in the speak function)
text_to_speech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS){
int result = text_to_speech.setLanguage(Locale.ENGLISH);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
Log.e("TTS", "Language not supported");
} else {
ttsIsInitialized = true; // flag tts as initialized
}
} else {
Log.e("TTS", "Failed");
}
}
});
}
public void speak(String text){
if (!ttsIsInitialized) {return;}
text_to_speech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}