0

我在 Android 上提出了一个问题,但没有得到任何答案,但我在 iPhone 平台上发现了一个类似的问题,但我不知道如何将其转换为 Java 代码。请精通这两种语言的任何人都可以尝试一下。

NSString* userAgent = @"Mozilla/5.0";

NSURL *url = [NSURL URLWithString:[@"http://www.translate.google.com/translate_tts?tl=el&q=Καλημέρα" 
                        stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease];

[request setValue:userAgent forHTTPHeaderField:@"User-Agent"];

NSURLResponse* response = nil;
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request
                                 returningResponse:&response
                                             error:&error];


[data writeToFile:@"/var/tmp/tts.mp3" atomically:YES];
4

2 回答 2

1

好的,我想通了,(据我所知)

他正在尝试从网络下载文件并将其保存到 i-phone 的本地存储中,

在android中试试这段代码,

try {
        URL url = new URL("http://www.translate.google.com/translate_tts?tl=el&q=Καλημέρα");
        URLConnection connection = url.openConnection();
        connection.connect();
        // this will be useful so that you can show a typical 0-100% progress bar
        int fileLength = connection.getContentLength();

        // download the file
        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream("/sdcard/tts.mp3");

        byte data[] = new byte[1024];
       int count;
        while ((count = input.read(data)) != -1) {
            output.write(data, 0, count);
        }
       output.flush();
        output.close();
        input.close();
    } catch (Exception e) {
    }

还要在您的 Android Manifest.xml 文件中提及 Use-Permission,例如,

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

现在,这会将您下载的 mp3 文件存储在外部存储中。

于 2012-04-20T12:24:52.273 回答
0
HttpClient httpclient = new DefaultHttpClient();

HttpGet httpget = new HttpGet("http://www.translate.google.com/translate_tts?tl=el&q=Καλημέρα");

HttpResponse response = httpclient.execute(httpget);

然后从响应中获取文件?抱歉,我的 atm 没有 IDE。

也许是这样的?

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(response.getEntity().getContent());

我不知道如何解析 mp3 文件?

怎么样的东西

InputStream is = response.getEnitity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
   baf.append((byte) current);
}

FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
于 2012-04-20T12:16:05.403 回答