2

我在 .it 上尝试了相同的代码,Android 2.3效果很好。我记得我已经用了 with Android 4.0。现在在Nexus 4Nexus 7上尝试使用Android 4.4.2onInit 方法的应用程序不会被调用。有人告诉我会知道这样做的原因,还是建议其他实施方法?

public class MyFragment extends Fragment implements TextToSpeech.OnInitListener{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_recognition, container, false);

        return v;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // check for TTS data
        Intent checkTTSIntent = new Intent();
        checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        if(myTTS != null) {
            myTTS.stop();
            myTTS.shutdown();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == MY_DATA_CHECK_CODE) {
            if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
                // the user has the necessary data - create the TTS
                myTTS = new TextToSpeech(getActivity(), this);
            } else {
                //no data - install it now
                Intent installTTSIntent = new Intent();
                installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installTTSIntent);
            }
        }
    }

    // setup TTS
    public void onInit(int initStatus) {
        // check for successful instantiation
        // if (initStatus == TextToSpeech.SUCCESS) {
        // if(myTTS.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE)
        myTTS.setLanguage(Locale.ITALIAN);
        // }
        // else if (initStatus == TextToSpeech.ERROR) {
        // Toast.makeText(this, "Sorry! Text To Speech failed...",
        // Toast.LENGTH_LONG).show();
        // }
        speak("Sintesi Vocale Attiva");
    }

    private void speak(String speech) {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put(TextToSpeech.Engine.KEY_FEATURE_NETWORK_SYNTHESIS, "true");
        myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, hashMap);
    }
}
4

3 回答 3

4

当您在 Android 4.4.2 中初始化 TTS 引擎时,似乎存在一些与 AsyncTask 处理相关的问题。

如果其他人遇到这个问题,我建议等到调用 onInit 方法并使用一些循环检查这个条件,然后继续启动 AsyncTask 进程(即使它们与 TTS 无关)。这至少对我有用......

于 2014-03-17T20:45:47.420 回答
3

已解决的问题:我不知道为什么,但是消除了对启动 AsyncTask 的方法的调用,一切都解决了。该方法在onCreateView中调用,与TTS无关,根据需要接收UDP数据报。

于 2014-01-21T08:20:27.033 回答
-1

作为一种解决方法,您可以启动一个计时器任务来延迟异步任务的启动,直到文本到语音的初始化之后。计时器任务应该启动一个可运行的,它确实从 UI 线程启动您的异步任务。就我而言,延迟一秒钟就可以了。

于 2015-11-05T13:17:22.600 回答