适用于阿拉伯语,中文和希腊语的Google TTS API

时间:2012-04-21 00:33:06

标签: android http-headers google-api httprequest user-agent

我正在尝试从谷歌TTS API下载一个mp3文件,这是代码

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


    }

这很好用,但是当我尝试使用特殊字符的中文或希腊语等语言时

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

我回来的mp3文件没有声音,但从文件的大小我可以告诉它有数据。当我尝试用阿拉伯语

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

我找回一个0字节的空mp3文件。

我尝试过使用不同的用户代理,似乎没有任何工作。

请帮忙。

谢谢

3 个答案:

答案 0 :(得分:3)

将路径用作URI而不是字符串,然后将其更改为ascii字符串。

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

URL u = new URL(uri.toASCIIString());

答案 1 :(得分:1)

我有同样的问题。但我昨天已经解决了。 我想API说中文并保存到mp3文件。

网址现在是: path =“http://translate.google.com/translate_tts?tl=zh-TW&q=你好” 你这样做: path =“http://translate.google.com/translate_tts?ie=UTF-8&tl=zh-TW&q=”.urlencode(“你好”);

添加一个参数ie = utf-8并对中文单词进行编码。 你会得到你想要的东西。

答案 2 :(得分:0)

如果应用程序崩溃请尝试此

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

它取代了单词之间的空格。

相关问题