适用于阿拉伯语、中文和希腊语的谷歌 TTS API



我正在尝试从谷歌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";

我得到一个空的 mp3 文件,其中包含 0 字节。

我尝试使用不同的用户代理,但似乎没有任何效果。

请帮忙。

谢谢

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

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

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

网址现在为:路径="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("你好");

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

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

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

它替换了单词之间的空格。

最新更新