Saturday, September 13, 2014

Google Translate (with tts) on JavaFX, using java-google-translate-text-to-speech

This example show how to implement Google Translate, with text-to-speech, on JavaFX application, using java-google-translate-text-to-speech.


Read the post "JavaFX with text-to-speech, with java-google-translate-text-to-speech" to know how to add lib of java-google-translate-text-to-speech for Netbeans.

package javafx_texttospeech;

import com.gtranslate.Audio;
import com.gtranslate.Language;
import com.gtranslate.Translator;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.TilePane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javazoom.jl.decoder.JavaLayerException;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_TextToSpeech extends Application {
    
    Lang lang;
    ObservableList langNameList;
    ObservableList langPrefixList;
    
    String selectedPrefix;
    String srcPrefix = Language.ENGLISH;

    @Override
    public void start(Stage primaryStage) {
        
        lang = new Lang();
        langNameList = lang.getNameList();
        langPrefixList = lang.getPrefixList();

        Label labelPrefix = new Label();
        
        ChoiceBox targetLangBox = new ChoiceBox(langNameList);
        targetLangBox.getSelectionModel().selectFirst();
        
        Label labelTranslated = new Label();
        
        selectedPrefix = (String) langPrefixList.get(
            targetLangBox.getSelectionModel().getSelectedIndex());
        labelPrefix.setText(selectedPrefix);
        
        targetLangBox.getSelectionModel().selectedIndexProperty()
            .addListener(new ChangeListener(){

            @Override
            public void changed(ObservableValue observable, 
                Object oldValue, Object newValue) {
                
                selectedPrefix = (String) langPrefixList.get((int)newValue);
                labelPrefix.setText(selectedPrefix);
            }
        });

        TextField srcTextField = new TextField();
        
        Button btnTranslate = new Button("Translate");
        btnTranslate.setOnAction((ActionEvent event) -> {
            Translator translator = Translator.getInstance();
            String translatedText = translator.translate(
                    srcTextField.getText(), 
                    srcPrefix, 
                    selectedPrefix);
            labelTranslated.setText(translatedText);
        });
        
        Button btnSpeakSrc = new Button("Speak");
        btnSpeakSrc.setOnAction((ActionEvent event) -> {
            String toSpeak = srcTextField.getText();
            if(!toSpeak.equals("")){
                try {
                    InputStream sound = null;
                    Audio audio = Audio.getInstance();
                    sound = audio.getAudio(toSpeak, srcPrefix);
                    audio.play(sound);
                } catch (IOException ex) {
                    Logger.getLogger(JavaFX_TextToSpeech.class.getName()).log(Level.SEVERE, null, ex);
                } catch (JavaLayerException ex) {
                    Logger.getLogger(JavaFX_TextToSpeech.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
        });
        
        Button btnSpeakDest = new Button("Speak");
        btnSpeakDest.setOnAction((ActionEvent event) -> {
            
            String toSpeak = labelTranslated.getText();
            if(!toSpeak.equals("")){
                try {
                    InputStream sound = null;
                    Audio audio = Audio.getInstance();
                    sound = audio.getAudio(toSpeak, selectedPrefix);
                    audio.play(sound);
                } catch (IOException ex) {
                    Logger.getLogger(JavaFX_TextToSpeech.class.getName()).log(Level.SEVERE, null, ex);
                } catch (JavaLayerException ex) {
                    Logger.getLogger(JavaFX_TextToSpeech.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            
        });
        
        VBox vBoxSrc = new VBox();
        VBox vBoxDest = new VBox();
        vBoxSrc.getChildren().addAll(
            new Label("Source: ENGLISH (en)"), 
            srcTextField, 
            btnTranslate, 
            btnSpeakSrc);
        
        vBoxDest.getChildren().addAll(
            new Label("Translate to:"), 
            targetLangBox, 
            labelPrefix, 
            labelTranslated, 
            btnSpeakDest);

        TilePane tilePane = new TilePane();
        tilePane.setPrefColumns(3);
        tilePane.setPadding(new Insets(5, 5, 5, 5));
        tilePane.setVgap(5);
        tilePane.setHgap(5);
        tilePane.setStyle("-fx-background-color: D0D0D0;");
        tilePane.setAlignment(Pos.TOP_CENTER);

        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                InputStream sound = null;
                try {
                    System.out.println("Hello World!");
                    Audio audio = Audio.getInstance();
                    sound = audio.getAudio("Hello World", Language.ENGLISH);
                    audio.play(sound);
                } catch (IOException | JavaLayerException ex) {
                    Logger.getLogger(JavaFX_TextToSpeech.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    try {
                        sound.close();
                    } catch (IOException ex) {
                        Logger.getLogger(JavaFX_TextToSpeech.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        });

        tilePane.getChildren().addAll(vBoxSrc, vBoxDest);

        StackPane root = new StackPane();
        root.getChildren().add(tilePane);

        Scene scene = new Scene(root, 500, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

class Lang {

    private Map<String, String> mapLang;

    Lang() {
        mapLang = new TreeMap<>();
        init();
    }

    private void init() {
        mapLang.put("af", "AFRIKAANS");
        mapLang.put("sq", "ALBANIAN");
        mapLang.put("ar", "ARABIC");
        mapLang.put("hy", "ARMENIAN");
        mapLang.put("az", "AZERBAIJANI");
        mapLang.put("eu", "BASQUE");
        mapLang.put("be", "BELARUSIAN");
        mapLang.put("bn", "BENGALI");
        mapLang.put("bg", "BULGARIAN");
        mapLang.put("ca", "CATALAN");
        mapLang.put("zh-CN", "CHINESE");
        mapLang.put("hr", "CROATIAN");
        mapLang.put("cs", "CZECH");
        mapLang.put("da", "DANISH");
        mapLang.put("nl", "DUTCH");
        mapLang.put("en", "ENGLISH");
        mapLang.put("et", "ESTONIAN");
        mapLang.put("tl", "FILIPINO");
        mapLang.put("fi", "FINNISH");
        mapLang.put("fr", "FRENCH");
        mapLang.put("gl", "GALICIAN");
        mapLang.put("ka", "GEORGIAN");
        mapLang.put("de", "GERMAN");
        mapLang.put("el", "GREEK");
        mapLang.put("gu", "GUJARATI");
        mapLang.put("ht", "HAITIAN_CREOLE");
        mapLang.put("iw", "HEBREW");
        mapLang.put("hi", "HINDI");
        mapLang.put("hu", "HUNGARIAN");
        mapLang.put("is", "ICELANDIC");
        mapLang.put("id", "INDONESIAN");
        mapLang.put("ga", "IRISH");
        mapLang.put("it", "ITALIAN");
        mapLang.put("ja", "JAPANESE");
        mapLang.put("kn", "KANNADA");
        mapLang.put("ko", "KOREAN");
        mapLang.put("la", "LATIN");
        mapLang.put("lv", "LATVIAN");
        mapLang.put("lt", "LITHUANIAN");
        mapLang.put("mk", "MACEDONIAN");
        mapLang.put("ms", "MALAY");
        mapLang.put("mt", "MALTESE");
        mapLang.put("no", "NORWEGIAN");
        mapLang.put("fa", "PERSIAN");
        mapLang.put("pl", "POLISH");
        mapLang.put("pt", "PORTUGUESE");
        mapLang.put("ro", "ROMANIAN");
        mapLang.put("ru", "RUSSIAN");
        mapLang.put("sr", "SERBIAN");
        mapLang.put("sk", "SLOVAK");
        mapLang.put("sl", "SLOVENIAN");
        mapLang.put("es", "SPANISH");
        mapLang.put("sw", "SWAHILI");
        mapLang.put("sv", "SWEDISH");
        mapLang.put("ta", "TAMIL");
        mapLang.put("te", "TELUGU");
        mapLang.put("th", "THAI");
        mapLang.put("tr", "TURKISH");
        mapLang.put("uk", "UKRAINIAN");
        mapLang.put("ur", "URDU");
        mapLang.put("vi", "VIETNAMESE");
        mapLang.put("cy", "WELSH");
        mapLang.put("yi", "YIDDISH");
        mapLang.put("af", "AFRIKAANS");
        mapLang.put("sq", "ALBANIAN");
        mapLang.put("ar", "ARABIC");
        mapLang.put("hy", "ARMENIAN");
        mapLang.put("az", "AZERBAIJANI");
        mapLang.put("eu", "BASQUE");
        mapLang.put("be", "BELARUSIAN");
        mapLang.put("bn", "BENGALI");
        mapLang.put("bg", "BULGARIAN");
        mapLang.put("ca", "CATALAN");
        mapLang.put("zh-CN", "CHINESE_SIMPLIFIED");
        mapLang.put("zh-TW", "CHINESE_TRADITIONAL");
        mapLang.put("hr", "CROATIAN");
        mapLang.put("cs", "CZECH");
        mapLang.put("da", "DANISH");
        mapLang.put("nl", "DUTCH");
        mapLang.put("et", "ESTONIAN");
        mapLang.put("tl", "FILIPINO");
        mapLang.put("fi", "FINNISH");
        mapLang.put("fr", "FRENCH");
        mapLang.put("gl", "GALICIAN");
        mapLang.put("ka", "GEORGIAN");
        mapLang.put("de", "GERMAN");
        mapLang.put("el", "GREEK");
        mapLang.put("gu", "GUJARATI");
        mapLang.put("ht", "HAITIAN_CREOLE");
        mapLang.put("iw", "HEBREW");
        mapLang.put("hi", "HINDI");
        mapLang.put("hu", "HUNGARIAN");
        mapLang.put("is", "ICELANDIC");
        mapLang.put("id", "INDONESIAN");
        mapLang.put("ga", "IRISH");
        mapLang.put("it", "ITALIAN");
        mapLang.put("ja", "JAPANESE");
        mapLang.put("kn", "KANNADA");
        mapLang.put("ko", "KOREAN");
        mapLang.put("la", "LATIN");
        mapLang.put("lv", "LATVIAN");
        mapLang.put("lt", "LITHUANIAN");
        mapLang.put("mk", "MACEDONIAN");
        mapLang.put("ms", "MALAY");
        mapLang.put("mt", "MALTESE");
        mapLang.put("no", "NORWEGIAN");
        mapLang.put("fa", "PERSIAN");
        mapLang.put("pl", "POLISH");
        mapLang.put("pt", "PORTUGUESE");
        mapLang.put("ro", "ROMANIAN");
        mapLang.put("ru", "RUSSIAN");
        mapLang.put("sr", "SERBIAN");
        mapLang.put("sk", "SLOVAK");
        mapLang.put("sl", "SLOVENIAN");
        mapLang.put("es", "SPANISH");
        mapLang.put("sw", "SWAHILI");
        mapLang.put("sv", "SWEDISH");
        mapLang.put("ta", "TAMIL");
        mapLang.put("te", "TELUGU");
        mapLang.put("th", "THAI");
        mapLang.put("tr", "TURKISH");
        mapLang.put("uk", "UKRAINIAN");
        mapLang.put("ur", "URDU");
        mapLang.put("vi", "VIETNAMESE");
        mapLang.put("cy", "WELSH");
        mapLang.put("yi", "YIDDISH");
 
    }
    
    public ObservableList getNameList(){

        return FXCollections.observableArrayList(mapLang.values().toArray());

    }
    
    public ObservableList getPrefixList(){

        return FXCollections.observableArrayList(mapLang.keySet().toArray());

    }

}

3 comments: