How to use Google Translate's Text to Speech (TTS) services in your web page using Servlet

Thursday November 17, 2011 ()

This is complete working servlet that demonstrates how to use Google Translate's Text to Speech services. Google Translate TTS is able to translate text to clear voice for many different languages.

As a demo, please click play to speak the next sentence.

Loading the player ...

Here is the general format of the web services URL.

tl is the text language and q is the text that is to be spoken. Please visit Google Translate if the language you want to use is supported and change line 37 in the servlet code that follows for your language.

The web service returns an MP3 audio stream if the request is successful.

The Servlet

There is no special trick in this servlet except that you have to have a User-agent and NO Referer when connecting to the web services to avoid 403 and 404 errors respectively.

We use the same standard URL/URLConnection classes.

package kauswagan;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GoogleTTS extends HttpServlet {

    String GURL =

    protected void doGet(HttpServletRequest request,
        HttpServletResponse response)
            throws ServletException, IOException {

        speak(request, response);


    public void speak(HttpServletRequest request,
            HttpServletResponse response) throws
            ServletException, IOException {

        final String text = request.getParameter("text");

        URL url = new URL(GURL
                + text.replace(" ", "%20") + "&tl=en");

        URLConnection urlConn = url.openConnection();
        urlConn.addRequestProperty("User-Agent", "Mozilla");

        InputStream audioSrc = urlConn.getInputStream();
        DataInputStream read = new DataInputStream(audioSrc);

        ServletOutputStream out = response.getOutputStream();

        int b = 0;
        int c;

        while ((c = != -1) {

        read.close(); audioSrc.close();




The Servlet Descriptors



Player embed code.

    <div style="width:30px;height:30px;" id="jplayer">
          Loading the player ...</div>

    <script type="text/javascript">
            autostart: false,
            controlbar: "none",
            file: "/kauswagan/GoogleTTS?text=#{evNewsBlogsBean.titlex}",
            flashplayer: "./jw-5.8/player.swf",
            menu: false,
            volume: 80,
            width: 30,
            height: 30,
            provider: "sound"

Line 9 shown above is the call to our servlet and the text parameter which is the text we want spoken. We are using JWPlayer to play the voice. Use your favorite player as desired.

That's it. Good luck.


Comments (How to use Google Translate's Text to Speech (TTS) services in your web page using Servlet)