Java: download Text to Speech from Google Translate

筅森魡賤 提交于 2019-12-21 17:15:22

问题


I am trying to download text to speech from Google Translate using Java. It works fine with English language, but with Japanese it is not successful. Following is my code:

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());
}

Do you have any idea or suggestion?


回答1:


It seems that you need to tell Google that the search term contains UTF-8 encoded characters.

Changing your URL to http://translate.google.com/translate_tts?ie=UTF-8&tl=ja&q= fixes the problem for me. I get the same .mp3 downloaded as compared to the audio translation from the Google Translate site.



来源:https://stackoverflow.com/questions/13339421/java-download-text-to-speech-from-google-translate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!