setOnUtteranceProgressListener根本不适用于API> 21的文本到语音

setOnUtteranceProgressListener根本不适用于API> 21的文本到语音,第1张

setOnUtteranceProgressListener根本不适用于API> 21的文本到语音

主要问题是:

1)在初始化tts之前设置进度监听器

2)尝试用后台线程制作Toast。

我还有其他建议的更改,但不是必需的:

public class MainActivity extends AppCompatActivity {    String message = "How may I help you?";    String mostRecentUtteranceID;    private TextToSpeech myTTS;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        myTTS = new TextToSpeech(this, new TextToSpeech.onInitListener() { @Override public void onInit(int status) {     if(myTTS.getEngines().size() == 0){         Toast.makeText(MainActivity.this,"No Engines Installed",Toast.LENGTH_LONG).show();     }else{         if (status == TextToSpeech.SUCCESS){  ttsInitialized();         }     } }        });    }    private void ttsInitialized() {        // *** set UtteranceProgressListener AFTER tts is initialized ***        myTTS.setonUtteranceProgressListener(new UtteranceProgressListener() { @Override public void onStart(String utteranceId) { } @Override // this method will always called from a background thread. public void onDone(String utteranceId) {     // only respond to the most recent utterance     if (!utteranceId.equals(mostRecentUtteranceID)) {          Log.i("XXX", "onDone() blocked: utterance ID mismatch.");         return;      } // else continue...     boolean wasCalledFromBackgroundThread = (Thread.currentThread().getId() != 1);     Log.i("XXX", "was onDone() called on a background thread? : " + wasCalledFromBackgroundThread);     Log.i("XXX", "onDone working.");     // for demonstration only... avoid references to      // MainActivity (unless you use a WeakReference)     // inside the onDone() method, as it     // can cause a memory leak.     runonUiThread(new Runnable() {         @Override         public void run() {  // *** toast will not work if called from a background thread ***  Toast.makeText(MainActivity.this,"onDone working.",Toast.LENGTH_LONG).show();         }     }); } @Override public void onError(String utteranceId) { }        });        // set Language        myTTS.setLanguage(Locale.US);        // set unique utterance ID for each utterance        mostRecentUtteranceID = (new Random().nextInt() % 9999999) + ""; // "" is String force        // set params        // *** this method will work for more devices: API 19+ ***        HashMap<String, String> params = new HashMap<>();        params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, mostRecentUtteranceID);        myTTS.speak(message,TextToSpeech.QUEUE_FLUSH,params);    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5461893.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存