iPhone SDK - Google TTS and encoding

后端 未结 1 334
南旧
南旧 2020-12-04 18:40

I am developing a text-to-speech iphone app that support multi-languages.

Here is my request URL

requestUrlStr = @\"http://www.translate.google.com/t         


        
相关标签:
1条回答
  • 2020-12-04 19:24

    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];
    

    The ...delegate:nil delegateQueue:[NSOperationQueue mainQueue] can be omitted.

    0 讨论(0)
提交回复
热议问题