如何知道 TTS 何时完成?

发布于 2024-10-11 07:10:45 字数 81 浏览 3 评论 0原文

我正在 Android 上实现交互式语音响应应用程序。我想知道如何确定 tts.speak() 函数何时完成通话,以便我可以调用我的语音识别器函数。

I'm implementing an Interactive Voice Response application on Android. I would like to know how to determine when the tts.speak() function has done talking so I can call my speech recognizer function.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

绝不服输 2024-10-18 07:10:45
public class TTSActivity extends Activity implements OnInitListener, OnUtteranceCompletedListener, ... {
private TextToSpeech mTts;
...........
private void speak(String text) {
   if(text != null) {
      HashMap<String, String> myHashAlarm = new HashMap<String, String>();
      myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_ALARM));
      myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "SOME MESSAGE");
      mTts.speak(text, TextToSpeech.QUEUE_FLUSH, myHashAlarm);
   }
}
// Fired after TTS initialization
public void onInit(int status) {
    if(status == TextToSpeech.SUCCESS) {
        mTts.setOnUtteranceCompletedListener(this);
    }
}
// It's callback
public void onUtteranceCompleted(String utteranceId) {
   Log.i(TAG, utteranceId); //utteranceId == "SOME MESSAGE"
   }
...........
}

阅读 A很好的教程

public class TTSActivity extends Activity implements OnInitListener, OnUtteranceCompletedListener, ... {
private TextToSpeech mTts;
...........
private void speak(String text) {
   if(text != null) {
      HashMap<String, String> myHashAlarm = new HashMap<String, String>();
      myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_ALARM));
      myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "SOME MESSAGE");
      mTts.speak(text, TextToSpeech.QUEUE_FLUSH, myHashAlarm);
   }
}
// Fired after TTS initialization
public void onInit(int status) {
    if(status == TextToSpeech.SUCCESS) {
        mTts.setOnUtteranceCompletedListener(this);
    }
}
// It's callback
public void onUtteranceCompleted(String utteranceId) {
   Log.i(TAG, utteranceId); //utteranceId == "SOME MESSAGE"
   }
...........
}

Read A good tutorial

夜吻♂芭芘 2024-10-18 07:10:45

自 API 级别 15 起,setOnUtteranceCompletedListener 已被弃用。相反,请使用 setOnUtteranceProgressListener

我找到了一个代码片段(此处),它确实实现了我很容易知道文本到语音何时完成:

@Override
public void onInit(int status) {
    if (status == TextToSpeech.SUCCESS) {
        myTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
            @Override
            public void onDone(String utteranceId) {
                // Log.d("MainActivity", "TTS finished");
            }

            @Override
            public void onError(String utteranceId) {
            }

            @Override
            public void onStart(String utteranceId) {
            }
        });
    } else {
        Log.e("MainActivity", "Initilization Failed!");
    }
}

http:// www.codota.com/android/scenarios/52fcbd34da0ae25e0f855408/android.speech.tts.TextToSpeech?tag=dragonfly

The setOnUtteranceCompletedListener is deprecated since API level 15. Instead, use setOnUtteranceProgressListener.

I found a code snippet (here) that made it really easy for me to know when text to speech is finished:

@Override
public void onInit(int status) {
    if (status == TextToSpeech.SUCCESS) {
        myTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
            @Override
            public void onDone(String utteranceId) {
                // Log.d("MainActivity", "TTS finished");
            }

            @Override
            public void onError(String utteranceId) {
            }

            @Override
            public void onStart(String utteranceId) {
            }
        });
    } else {
        Log.e("MainActivity", "Initilization Failed!");
    }
}

http://www.codota.com/android/scenarios/52fcbd34da0ae25e0f855408/android.speech.tts.TextToSpeech?tag=dragonfly

草莓味的萝莉 2024-10-18 07:10:45

要知道 TTS 何时完成,您必须调用 setOnUtteranceProgressListener,它有 3 个回调方法 onStartonDoneonError >
然后将话语 ID 添加到 talk 方法

代码片段中

textToSpeech=new TextToSpeech(this, new TextToSpeech.OnInitListener() {
    @Override
    public void onInit(int status) {
        if (status==TextToSpeech.SUCCESS){
            int result=textToSpeech.setLanguage(Locale.ENGLISH);

            if (result==TextToSpeech.LANG_MISSING_DATA||result==TextToSpeech.LANG_NOT_SUPPORTED){
                Log.i("TextToSpeech","Language Not Supported");
            }

            textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
                @Override
                public void onStart(String utteranceId) {
                    Log.i("TextToSpeech","On Start");
                }

                @Override
                public void onDone(String utteranceId) {
                    Log.i("TextToSpeech","On Done");
                }

                @Override
                public void onError(String utteranceId) {
                    Log.i("TextToSpeech","On Error");
                }
            });

        }else {
            Log.i("TextToSpeech","Initialization Failed");
        }
    }
});


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null,TextToSpeech.ACTION_TTS_QUEUE_PROCESSING_COMPLETED);
    }

To know when TTS is finished you have to call the setOnUtteranceProgressListener which has 3 call back methods onStart,onDone and onError
then include a Utterance Id to the speak method

Code Snippet

textToSpeech=new TextToSpeech(this, new TextToSpeech.OnInitListener() {
    @Override
    public void onInit(int status) {
        if (status==TextToSpeech.SUCCESS){
            int result=textToSpeech.setLanguage(Locale.ENGLISH);

            if (result==TextToSpeech.LANG_MISSING_DATA||result==TextToSpeech.LANG_NOT_SUPPORTED){
                Log.i("TextToSpeech","Language Not Supported");
            }

            textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
                @Override
                public void onStart(String utteranceId) {
                    Log.i("TextToSpeech","On Start");
                }

                @Override
                public void onDone(String utteranceId) {
                    Log.i("TextToSpeech","On Done");
                }

                @Override
                public void onError(String utteranceId) {
                    Log.i("TextToSpeech","On Error");
                }
            });

        }else {
            Log.i("TextToSpeech","Initialization Failed");
        }
    }
});


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null,TextToSpeech.ACTION_TTS_QUEUE_PROCESSING_COMPLETED);
    }
暗藏城府 2024-10-18 07:10:45

我注意到有人在使用TextToSpeech时遇到问题来询问您的解决方案

如何知道TTS何时完成?
不使用 setOnUtteranceCompletedListener

public void isTTSSpeaking(){

    final Handler h =new Handler();

    Runnable r = new Runnable() {

        public void run() {

            if (!tts.isSpeaking()) {
                onTTSSpeechFinished();
            }

            h.postDelayed(this, 1000);
        }
    };

    h.postDelayed(r, 1000);
}

I noticed that there are people having problems in the use of TextToSpeech to ask that the solution to you

How to know when TTS is finished?
without use setOnUtteranceCompletedListener

public void isTTSSpeaking(){

    final Handler h =new Handler();

    Runnable r = new Runnable() {

        public void run() {

            if (!tts.isSpeaking()) {
                onTTSSpeechFinished();
            }

            h.postDelayed(this, 1000);
        }
    };

    h.postDelayed(r, 1000);
}
禾厶谷欠 2024-10-18 07:10:45

尝试下面的代码,它会在 TTS 完成后显示一个祝酒词。用自己的行动代替吐司。

public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener{


private boolean initialized;
private String queuedText;
private String TAG = "TTS";
private TextToSpeech tts;




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    tts = new TextToSpeech(this /* context */, this /* listener */);
    tts.setOnUtteranceProgressListener(mProgressListener);


    speak("hello world");

}




public void speak(String text) {

    if (!initialized) {
        queuedText = text;
        return;
    }
    queuedText = null;

    setTtsListener(); // no longer creates a new UtteranceProgressListener each time
    HashMap<String, String> map = new HashMap<String, String>();
    map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "MessageId");
    tts.speak(text, TextToSpeech.QUEUE_ADD, map);
}


private void setTtsListener() {

}





@Override
public void onInit(int status) {
    if (status == TextToSpeech.SUCCESS) {
        initialized = true;
        tts.setLanguage(Locale.ENGLISH);

        if (queuedText != null) {
            speak(queuedText);
        }
    }
}



private abstract class runnable implements Runnable {
}




private UtteranceProgressListener mProgressListener = new UtteranceProgressListener() {
    @Override
    public void onStart(String utteranceId) {
    } // Do nothing

    @Override
    public void onError(String utteranceId) {
    } // Do nothing.

    @Override
    public void onDone(String utteranceId) {

        new Thread()
        {
            public void run()
            {
                MainActivity.this.runOnUiThread(new runnable()
                {
                    public void run()
                    {

                        Toast.makeText(getBaseContext(), "TTS Completed", Toast.LENGTH_SHORT).show();

                    }
                });
            }
        }.start();

    }
}; }

Try this following code which shows a toast after TTS completed. Replace toast with your own action.

public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener{


private boolean initialized;
private String queuedText;
private String TAG = "TTS";
private TextToSpeech tts;




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    tts = new TextToSpeech(this /* context */, this /* listener */);
    tts.setOnUtteranceProgressListener(mProgressListener);


    speak("hello world");

}




public void speak(String text) {

    if (!initialized) {
        queuedText = text;
        return;
    }
    queuedText = null;

    setTtsListener(); // no longer creates a new UtteranceProgressListener each time
    HashMap<String, String> map = new HashMap<String, String>();
    map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "MessageId");
    tts.speak(text, TextToSpeech.QUEUE_ADD, map);
}


private void setTtsListener() {

}





@Override
public void onInit(int status) {
    if (status == TextToSpeech.SUCCESS) {
        initialized = true;
        tts.setLanguage(Locale.ENGLISH);

        if (queuedText != null) {
            speak(queuedText);
        }
    }
}



private abstract class runnable implements Runnable {
}




private UtteranceProgressListener mProgressListener = new UtteranceProgressListener() {
    @Override
    public void onStart(String utteranceId) {
    } // Do nothing

    @Override
    public void onError(String utteranceId) {
    } // Do nothing.

    @Override
    public void onDone(String utteranceId) {

        new Thread()
        {
            public void run()
            {
                MainActivity.this.runOnUiThread(new runnable()
                {
                    public void run()
                    {

                        Toast.makeText(getBaseContext(), "TTS Completed", Toast.LENGTH_SHORT).show();

                    }
                });
            }
        }.start();

    }
}; }
ζ澈沫 2024-10-18 07:10:45

通过这段代码我解决了这个问题。我希望只要有人说话,开始按钮就一直亮着。也许这会对某人有所帮助。

    public void _tts_speak_lenght() {
    t2 = new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (TTS.isSpeaking()) {
                        isSpeaking = true;
                    }
                    else {
                        if (!TTS.isSpeaking()) {
                            t2.cancel();
                            isSpeaking = false;
                            imgBtn_startReader.setImageResource(R.drawable.ic_start_off);
                        }
                    }
                }
            });
        }
    };
    _timer.scheduleAtFixedRate(t2, (int)(0), (int)(100));
}

With this code I solved the problem. I wanted the start button to stay lit as long as someone was speaking. Maybe this will help someone.

    public void _tts_speak_lenght() {
    t2 = new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (TTS.isSpeaking()) {
                        isSpeaking = true;
                    }
                    else {
                        if (!TTS.isSpeaking()) {
                            t2.cancel();
                            isSpeaking = false;
                            imgBtn_startReader.setImageResource(R.drawable.ic_start_off);
                        }
                    }
                }
            });
        }
    };
    _timer.scheduleAtFixedRate(t2, (int)(0), (int)(100));
}
过期以后 2024-10-18 07:10:45

使用这个监听器:

    textToSpeech.setOnUtteranceProgressListener(
        object : UtteranceProgressListener() {
            override fun onStart(utteranceId: String?) {
                Handler(Looper.getMainLooper()).post {
                    //if you want update ui you should use handler
                }
            }

            override fun onDone(utteranceId: String?) {
                Handler(Looper.getMainLooper()).post {
                    //if you want update ui you should use handler
                }
            }

            @Deprecated("Deprecated in Java")
            override fun onError(utteranceId: String?) {
                Handler(Looper.getMainLooper()).post {
                    //if you want update ui you should use handler
                }
            }
        }
    )

use this listener :

    textToSpeech.setOnUtteranceProgressListener(
        object : UtteranceProgressListener() {
            override fun onStart(utteranceId: String?) {
                Handler(Looper.getMainLooper()).post {
                    //if you want update ui you should use handler
                }
            }

            override fun onDone(utteranceId: String?) {
                Handler(Looper.getMainLooper()).post {
                    //if you want update ui you should use handler
                }
            }

            @Deprecated("Deprecated in Java")
            override fun onError(utteranceId: String?) {
                Handler(Looper.getMainLooper()).post {
                    //if you want update ui you should use handler
                }
            }
        }
    )
醉城メ夜风 2024-10-18 07:10:45

当文本说话时使用 SpeakableListener。

private volatile boolean finished;

private SpeakableListener listener = new SpeakableListener() {

    @Override
    public void markerReached(SpeakableEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void speakableCancelled(SpeakableEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void speakableEnded(SpeakableEvent arg0) {
        TestSpeaker.this.finished = true;

    }

    @Override
    public void speakablePaused(SpeakableEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void speakableResumed(SpeakableEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void speakableStarted(SpeakableEvent arg0) {
        TestSpeaker.this.finished = false;

    }

    @Override
    public void topOfQueue(SpeakableEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void wordStarted(SpeakableEvent arg0) {
        // TODO Auto-generated method stub

    }
};

/** Speak the following string. */
public void sayIt(String str) {
    System.out.print(" " + str + " ");
    /* The the synthesizer to speak. */
    synthesizer.speakPlainText(str, listener);

use a SpeakableListener when do text to speak.

private volatile boolean finished;

private SpeakableListener listener = new SpeakableListener() {

    @Override
    public void markerReached(SpeakableEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void speakableCancelled(SpeakableEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void speakableEnded(SpeakableEvent arg0) {
        TestSpeaker.this.finished = true;

    }

    @Override
    public void speakablePaused(SpeakableEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void speakableResumed(SpeakableEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void speakableStarted(SpeakableEvent arg0) {
        TestSpeaker.this.finished = false;

    }

    @Override
    public void topOfQueue(SpeakableEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void wordStarted(SpeakableEvent arg0) {
        // TODO Auto-generated method stub

    }
};

/** Speak the following string. */
public void sayIt(String str) {
    System.out.print(" " + str + " ");
    /* The the synthesizer to speak. */
    synthesizer.speakPlainText(str, listener);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文