Simple Text To Speech in Java based on Google Translate API

Google Translate is one of the most powerful Google Services, it helps us to translate text from one language to another language. The good thing is that it also pronounces the translating (or translated) text. You can try it yourself by using this link, for example:

https://translate.google.com/translate_tts?tl=en&q=Hello

Based on this idea, we’ll build a simple Java program which takes two input variables: language and text and outputs a mp3 file of text in language.

The program is very straightforward and self-explained, it just takes 86 lines of codes and can be found here:

package com.nxhoaf;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class SimpleTextToSpeech {
    private static final String TEXT_TO_SPEECH_SERVICE = 
            "http://translate.google.com/translate_tts";
    private static final String USER_AGENT =  
            "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) " +
            "Gecko/20100101 Firefox/11.0";

    public static void main(String[] args) throws Exception {
        if (args.length != 2) {
            System.out.println("Usage: SimpleTextToSpeech <language> <text> " +
                    "where: ");
            System.out.println();
            System.out.println("- Language: all languages accepted by " +
                    "google translate, in this example, we'll use fr, en");
            System.out.println("- Text : If text is more than one word, " +
                    "then is must be put inside double quote, for example:");
            System.out.println("\tjava SimpleTextToSpeech en Hello");
            System.out.println("\tjava SimpleTextToSpeech en \"Hello World\"");
            System.exit(1);
        }
        Language language = Language.valueOf(args[0].toUpperCase());
        String text = args[1];
        text = URLEncoder.encode(text, "utf-8");
        new SimpleTextToSpeech().go(language, text);
    }

    public void go(Language language, String text) throws Exception {
        // Create url based on input params
        String strUrl = TEXT_TO_SPEECH_SERVICE + "?" + 
                "tl=" + language + "&q=" + text;
        URL url = new URL(strUrl);

        // Etablish connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // Get method
        connection.setRequestMethod("GET");
        // Set User-Agent to "mimic" the behavior of a web browser. In this 
        // example, I used my browser's info
        connection.addRequestProperty("User-Agent", USER_AGENT);
        connection.connect();

        // Get content
        BufferedInputStream bufIn = 
                new BufferedInputStream(connection.getInputStream());
        byte[] buffer = new byte[1024];
        int n;
        ByteArrayOutputStream bufOut = new ByteArrayOutputStream();
        while ((n = bufIn.read(buffer)) > 0) {
            bufOut.write(buffer, 0, n);
        }

        // Done, save data
        File output = new File("output.mp3");
        BufferedOutputStream out = 
                new BufferedOutputStream(new FileOutputStream(output));
        out.write(bufOut.toByteArray());
        out.flush();
        out.close();
        System.out.println("Done");
    }

    public enum Language {
        FR("french"),
        EN("english");

        private final String language;
        private Language(String language) {
            this.language = language;
        }

        public String getFullName() {
            return language;
        }
    }
}

Note that here, I used only English and French as input languages. Of course, it isn’t difficult to add another languages to the program (In fact, you can add as many languages as you want, as soon as it’s supported by Google Translate).

Advertisements
This entry was posted in Java and tagged . Bookmark the permalink.

2 Responses to Simple Text To Speech in Java based on Google Translate API

  1. zukedog says:

    How would I be able to do this offline?

  2. nxhoaf says:

    As you can see, we need google service to do it. To do it offline, we can save the text in some folders, as soon as there are network connection, we will scan that folder then send the content to google service. However, I havent tried the above idea yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s