iPhone SDK-Google TTS和编码 [英] iPhone SDK - Google TTS and encoding
问题描述
我正在开发支持多国语言的文本语音iphone应用.
I am developing a text-to-speech iphone app that support multi-languages.
这是我的请求网址
requestUrlStr = @"http://www.translate.google.com/translate_tts?tl=en&q=hello";
对于英语,上述网址没有问题
for english the above url has no problem
但对于中文
requestUrlStr = @"http://www.translate.google.com/translate_tts?tl=zh-TW&q=你好";
我知道上面的URL会给出错误的URL",因此我使用了follow方法将字符串编码为UTF-8
I know the above url will give 'Bad URL', so I used follow method to encode the string into UTF-8
requestUrlStr = [requestUrlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
它将变为
http://www.translate.google.com/translate_tts?tl=zh-CN&q=%E4%BD%A0%E5%A5%BD
然后Google TTS无法识别此中文文本.
Then the Google TTS cannot recognize this Chinese text.
推荐答案
您必须假装自己是NSURLRequest中的默认用户(appName等)以外的User-Agent.试试这个(我用希腊语)...
You have to pretend to be a User-Agent other than the default (appName, etc) in your NSURLRequest. Try this (I use Greek language) ...
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];
UPDATE 2017
由于我们最喜欢的公司喜欢更新和弃用事物,因此以下是上面的示例,因为现在应该如此...
Since our favorite companies enjoy to update and deprecate things, here is the above example as it should be now...
NSString* text = @"καλημέρα";
NSString* lang = @"el";
NSString* sUrl = [NSString stringWithFormat:@"https://translate.google.com/translate_tts?q=%@&tl=%@&client=tw-ob", text, lang];
sUrl = [sUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSURL* url = [NSURL URLWithString:sUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[request setValue:@"Mozilla/5.0" forHTTPHeaderField:@"User-Agent"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
delegate:nil
delegateQueue:[NSOperationQueue mainQueue]];
[[session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
[data writeToFile:@"/var/tmp/tts.mp3" atomically:YES];
}
] resume];
...delegate:nil delegateQueue:[NSOperationQueue mainQueue]
可以省略.
这篇关于iPhone SDK-Google TTS和编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!