0

我想根据 TTS 的状态 Toast 一条消息。为此,我使用了 OnUtteranceProgressListener() 。但我没有得到结果。我怎样才能完成这项任务?

下面给出的代码用于初始化 TTS 类。

textToSpeech=new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int i) {
               //Check if initialisation is successful
               if(i==TextToSpeech.SUCCESS)
               {
                   //set Language
                   int result=textToSpeech.setLanguage(Locale.ENGLISH);
                    //Check if language is set successfully or not.
                   if(result==TextToSpeech.LANG_NOT_SUPPORTED||result==TextToSpeech.LANG_MISSING_DATA)
                   {
                       Toast.makeText(MainActivity.this, "Language not supported", Toast.LENGTH_SHORT).show();
                   }
                   else{
                       Toast.makeText(MainActivity.this, "Welcome", Toast.LENGTH_SHORT).show();
                       textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
                           @Override
                           public void onStart(String s) {
                               Toast.makeText(MainActivity.this, "Started", Toast.LENGTH_SHORT).show();
                           }

                           @Override
                           public void onDone(String s) {
                               Toast.makeText(MainActivity.this,"Done",Toast.LENGTH_SHORT).show();

                           }

                           @Override
                           public void onError(String s) {
                               Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
                           }
                       });
                   }

               }
               else{
                   Toast.makeText(MainActivity.this, "Initialisation failed", Toast.LENGTH_SHORT).show();
               }
            }
        });

下面给出的代码用于触发事件

btnSpeak.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View view) {
                 speak();
             }
         });

speak() 函数定义:

private void speak() {
        String text="Good Morning";
        float pitch=(float)seekBarPitch.getProgress()/50;
        float speed=(float)seekBarSpeed.getProgress()/50;
        textToSpeech.setPitch(pitch);
        textToSpeech.setSpeechRate(speed);
        textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null,"UTTERANCE_ID");
    }
4

1 回答 1

0

Toast 消息在后台线程中不起作用。所以我们必须使用 runOnUIThread(); 在 UI 线程上运行它。

于 2022-01-15T13:11:26.253 回答