As a developer at IDR Solutions I spend a lot of my time working on the JPedal Java PDF library and lately I have been improving functionality with text to speech. I thought it might be useful to show you how to implement text to speech in both JavaFX and Swing applications in this tutorial.
JavaFX
1. Download jars:
For the JavaFX application we are using the java-google-translate-text-to-speech jars.
Download both of the jars and add them to your JavaFX application:
2. Create GUI and add the functionality to the button:
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Audio audio = Audio.getInstance();
InputStream sound = null;
try {
sound = audio.getAudio(text.getText(), Language.ENGLISH);
} catch (IOException ex) {
Logger.getLogger(JavaFX_TextToSpeech.class.getName()).log(Level.SEVERE, null, ex);
}
try {
audio.play(sound);
} catch (JavaLayerException ex) {
Logger.getLogger(JavaFX_TextToSpeech.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
Using java-google-translate-text-to-speech jars you can also build simple translator where you can translate your content into other languages.
Java Swing
1. Download jars:
For the Swing application we are using the FreeTTS jars.
Download the freets-1.2.2-bin.zip. Unzip the folder and add the jars from \freetts-1.2.2-bin\freetts-1.2\lib location to your application.
2. Create GUI and add the functionality to the button:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
VoiceManager vm = VoiceManager.getInstance();
Voice voice = vm.getVoice("kevin16");
voice.allocate();
voice.speak(text.getText());
}
});
Find out how to implement text to speech functionality in our JPedal Java PDF Viewer in this tutorial.
Hopefully you found this guide useful. Let us know if you would like to see anymore like this in the future.
Our software libraries allow you to
Convert PDF to HTML in Java |
Convert PDF Forms to HTML5 in Java |
Convert PDF Documents to an image in Java |
Work with PDF Documents in Java |
Read and Write AVIF, HEIC, WEBP and other image formats |
I am getting the following:-
java.io.IOException: Server returned HTTP response code: 503 for URL: http://ipv4.google.com/sorry/IndexRedirect?continue=http://translate.google.com/translate_tts%3Fq%3DHello%2520World%26tl%3Den&q=CGMSBCnes6gY3Ma9vAUiGQDxp4NLtQVq8cs6ppwO6rZqdlfDtNq3DDM
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1840)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at com.gtranslate.Audio.getAudio(Audio.java:34)
Hi Cosmas,
Seems like it might be an exception with one of the Google jars. This article shows others who have encountered similar exceptions: https://code.google.com/archive/p/java-google-translate-text-to-speech/issues/8 and there is a solution mentioned at comment #4. Hope this helps.