Site iconJava PDF Blog

How to enable Text to Speech in JavaFX and Swing Applications

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.