Java:从Google Translate下载Text to Speech

时间:2012-11-12 06:51:10

标签: java text-to-speech

我正在尝试使用Java从Google翻译下载文本到语音。它适用于英语,但对于日语则不成功。以下是我的代码:

try{
            String word="〜のそばに";
            word=java.net.URLEncoder.encode(word, "UTF-8");
            URL url = new URL("http://translate.google.com/translate_tts?tl=ja&q="+word);
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            urlConn.addRequestProperty("User-Agent", "Mozilla/4.76");
            InputStream audioSrc = urlConn.getInputStream();
            DataInputStream read = new DataInputStream(audioSrc);
            OutputStream outstream = new FileOutputStream(new File("mysound.mp3"));
            byte[] buffer = new byte[1024];
            int len;
            while ((len = read.read(buffer)) > 0) {
                    outstream.write(buffer, 0, len);                    
            }
            outstream.close();              
}catch(IOException e){
           System.out.println(e.getMessage());
}

您有任何想法或建议吗?

1 个答案:

答案 0 :(得分:6)

您似乎需要告诉Google搜索字词包含UTF-8编码字符。

将您的网址更改为http://translate.google.com/translate_tts?ie=UTF-8&tl=ja&q=可以解决我的问题。与Google翻译网站的音频翻译相比,我获得的.mp3下载次数相同。