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
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());
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 .
and if the app crashes try this
txtToTranslate = txtToTranslate.replace(" ", "%20");
it replaces the spaces between the words.
来源:https://stackoverflow.com/questions/10255130/google-tts-api-for-arabic-chinese-and-greek