简体   繁体   中英

Multiple threads not working simultaneously

I have a java program in which I am using TTS (Text to speech), in there along with that I want an animated gif to come up on the screen. I am using Netbeans GUI builder, so I made up a new jpanel form and added the gif in a label in that form (java jpanel form), and after that I added this java as a jpanel to my main java file (by dragging and dropping). But the problem is that as soon as the TTS, starts to speak something it stops the animation of the gif. How to make it work together? Note: I am using freeTTS for converting text to speech

Code:

private static final String VOICENAME = "kevin16";
VoiceManager voiceManager = VoiceManager.getInstance();
.....
........
Voice voice;
voice = voiceManager.getVoice(VOICENAME);
voice.allocate();
....//Some code here
t4.setText("" + ran);  
voice.speak(t4.getText()); 
listenanum.setText("" + d);
listenanum.setVisible(false);

I had to look up the FreeTTS Javadoc, which confirms what I thought.

The speak method on Voice blocks until the spoken text is complete. The method speak(String) invokes speak(FreeTTSSpeakable speakable) , which has this Javadoc:

Speak the given queue item. This is a synchronous method that does not return until the speakable is completely spoken or has been cancelled.

However, in Swing, as long as you're doing one thing in the UI thread, it cannot do anything else. So your animation will stop because it also needs the UI thread to repaint the image.

Perhaps the best way to resolve this is to delve deeper into the speech API and use the processUtterance(Utterance u) method on Voice . This method is asynchronous; it returns immediately while the speech is done on a different speech output thread.

However a simpler solution to get you going is to call the speak method on a different thread.

final String textToSpeak = t4.getText();
Thread speechThread = new Thread(new Runnable() {
    public void run() {
        voice.speak(textToSpeak);
    }
});
speechThread.start();

Actually, it's better to use a thread pool than to start a new thread each time, but that goes beyond your immediate problem. You can search StackOverflow or look at java.util.concurrent.ThreadPoolExecutor for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM