我试图从一个简单的类调用文本到语音,我正在做图像操作由于文本到语音TextToSpeech需要上下文作为参数我不能传递这个给它
是否有解决方法
例如,您可以在简单类的构造函数中传递有效的Context
,然后您可以从简单类中使用TTS:
public class MySimpleClass implements TextToSpeech.OnInitListener {
private TextToSpeech tts;
private boolean ttsOk;
// The constructor will create a TextToSpeech instance.
MySimpleClass(Context context) {
tts = new TextToSpeech(context, this);
}
@Override
// OnInitListener method to receive the TTS engine status
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
ttsOk = true;
}
else {
ttsOk = false;
}
}
// A method to speak something
@SuppressWarnings("deprecation") // Support older API levels too.
public void speak(String text, Boolean override) {
if (ttsOk) {
if (override) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
else {
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
}
// Other code goes here...
}
根据确切的应用程序设计,Context
可以是Activity
或应用程序上下文。如果接收上下文引用的类的生命周期超过提供它的类的生命周期,则应该使用后者。例如,当对Activity
有引用的类仍然存在时,它可能会被销毁。这将影响垃圾收集和内存泄漏。
另一种选择是将所有TTS代码保留在Activity
中,这是在使用"简单类"代码时显示的,将"简单类"的引用传递给Activity
,并在Activity
中有一个公共方法来接收需要说话的文本:
public class MySimpleClass {
private MyActivity myActivity;
// The constructor receives a reference to the Activity.
MySimpleClass(MyActivity activity) {
myActivity = activity;
}
// Other code goes here...
myActivity.speak("Hello, Stackoverflow!");
}
当传递引用给Activity
时,应该考虑类的生命周期,并避免在Activity
销毁后仍然存在的类中使用引用。
另一种选择是为TTS代码创建一个单独的类。它将接受一个Context
作为构造函数参数,并提供一个方法来使用任何给定的文本。在回答另一个问题时,有一个简单的例子。