如何在无活动性类中使用textToSpeech?

时间:2019-06-07 10:52:30

标签: android text-to-speech

我有一个MainActivity类,在这里我想听听从非活动类调用的textToSpeech。 no活动类是自动调用的,因此为了能够通过构造函数发送上下文,我不对其进行调用。

这是没有活动的课程

public class SetTiredAction implements Action
{
    private TextToSpeech textToSpeech;
    @Override
    public void execute(State state)
    {
        MenuActivity activity = new MenuActivity();
        Log.i("TEIRE", "TIRED");

        textToSpeech = new TextToSpeech(activity.getContext(), new TextToSpeech.OnInitListener() 
        {
            @Override
            public void onInit(int status) 
            {
                if (status == TextToSpeech.SUCCESS) 
                {
                    int ttsLang = textToSpeech.setLanguage(Locale.US);
                    Log.i("TTS", "Initialization success.");
                 }
            }
        });
        textToSpeech.speak("Are you tired?", TextToSpeech.QUEUE_FLUSH, null, null);
        textToSpeech.shutdown();
    }
}

在MenuActivity类中,我有一个获取上下文的方法,但是却收到了错误调用目标异常。

我该如何解决这个问题?

0 个答案:

没有答案