我有我的类MyTTS
和此类中的方法speakout
。当我在类中调用它时,它可以正常工作,但是如果我在其他类中初始化该类,并且再次调用此方法后再也无法工作,它将给我
W / TextToSpeech:语音失败:未绑定到TTS引擎
这是我的类MyTTS.java:
TextToSpeech textToSpeech;
public MyTTS(Context context) {
textToSpeech=new TextToSpeech(context,this);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void speakOut(String str,String pk){
textToSpeech.speak(str,TextToSpeech.QUEUE_FLUSH,null,pk);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
speakOut("badr","dfd");
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
@Override
public void onPause() {
if(textToSpeech==null){
textToSpeech.stop();
textToSpeech.shutdown();
}
super.onPause();
}
这是我初始化MyTTS类并调用talkOut方法的类:
fragment.java:
public class must_adapter_frag extends Fragment{
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@SuppressLint("JavascriptInterface")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Inflate the layout for this fragment
MyTTS myTTS=new MyTTS(getActivity());
View view= inflater.inflate(R.layout.webview_frag, container, false);
System.out.println("hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh");
myTTS.speakOut("salam","dj");
System.out.println("hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh");
WebView webView=view.findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(myTTS,"Android");
webView.loadUrl("file:///android_asset/"+String.valueOf(getArguments().getInt("position"))+".html");
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("تعليق");
}
如果有专家可以帮助我解决这个问题!
我很抱歉我的英语语言不是我的语言。
最佳答案
之所以会出现此错误,是因为MyTTS对象(从片段内部创建)中的TextToSpeech对象尚未初始化。
在MyTTS类中,您可以看到onInit()方法中有speakOut()。这就是为什么它在那里可以正常工作的原因...因为仅在初始化textToSpeech对象之后才调用onInit。
所以...您可以做的是:
public boolean textToSpeechIsInitialized = false; // <--- add this line
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
textToSpeechIsInitialized = true; // <--- add this line
int result = textToSpeech.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
speakOut("badr","dfd");
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
然后在您的片段中,确保在调用speakOut()之前先检查该布尔标志:
System.out.println("hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh");
if (myTTS.textToSpeechIsInitialized) { // <--- add this line
myTTS.speakOut("salam","dj");
} else {
// try again later
}