Google TTS API for Arabic, Chinese and Greek

匿名 (未验证) 提交于 2019-12-03 01:48:02

问题:

I am trying to download an mp3 file from google TTS API, here is the code

try {             String path ="http://translate.google.com/translate_tts?tl=en&q=hello";         //this is the name of the local file you will create         String targetFileName = "test.mp3";             boolean eof = false;         URL u = new URL(path);         HttpURLConnection c = (HttpURLConnection) u.openConnection();         c.addRequestProperty("User-Agent", "Mozilla/5.0");         c.setRequestMethod("GET");         c.setDoOutput(true);         c.connect();         FileOutputStream f = new FileOutputStream(new File(Environment.getExternalStorageDirectory()                 + "/download/"+targetFileName));             InputStream in = c.getInputStream();             byte[] buffer = new byte[1024];             int len1 = 0;             while ( (len1 = in.read(buffer)) > 0 ) {             f.write(buffer,0, len1);                      }         f.close();         } catch (MalformedURLException e) {         // TODO Auto-generated catch block         e.printStackTrace();         } catch (ProtocolException e) {         // TODO Auto-generated catch block         e.printStackTrace();         } catch (FileNotFoundException e) {         // TODO Auto-generated catch block         e.printStackTrace();         } catch (IOException e) {         // TODO Auto-generated catch block         e.printStackTrace();       }

This works fine, but when I try to make the request for languages like chinese or greek which use special characters

String path ="http://translate.google.com/translate_tts?tl=zh-TW&q=你好";

The mp3 file I get back has no sound but from the size of the file I can tell it has data in it. When I try the same with Arabic

String path ="http://translate.google.com/translate_tts?tl=ar&q=%D8%A7%D9%84%D9%84%D9%87";

I get back an empty mp3 file with 0 bytes.

I have tried using different user agents and nothing seems to work.

Please help.

Thank You

回答1:

Use the path as a URI rather than a string then change it to an ascii string.

URI uri = new URI("http://translate.google.com/translate_tts?tl=zh-TW&q=你好");  URL u = new URL(uri.toASCIIString());


回答2:

I have your same problem. But I have solve it yesterday. I wanna the API say Chinese and save to mp3 file .

The url now is: path ="http://translate.google.com/translate_tts?tl=zh-TW&q=你好" you do as follow: path ="http://translate.google.com/translate_tts?ie=UTF-8&tl=zh-TW&q=".urlencode("你好");

Add a param ie=utf-8 AND encode the Chinese words. You'll got what you want .



回答3:

and if the app crashes try this

txtToTranslate = txtToTranslate.replace(" ", "%20");

it replaces the spaces between the words.



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