在iOS上使用谷歌文字转语音(TTS)API

时间:2013-04-17 10:44:35

标签: iphone ios text-to-speech google-translate

我正在使用此代码的API:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"file.mp3"];

NSString *text = textToTranslate; //@"You are one chromosome away from being a potato.";
NSString *urlString = [NSString stringWithFormat:@"http://www.translate.google.com/translate_tts?tl=en&q=%@",text];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url] ;
[request setValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1" forHTTPHeaderField:@"User-Agent"];
NSURLResponse* response = nil;
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request
                                     returningResponse:&response
                                                 error:&error];
[data writeToFile:path atomically:YES];

SystemSoundID soundID;
NSURL *url2 = [NSURL fileURLWithPath:path];

AudioServicesCreateSystemSoundID((__bridge CFURLRef)url2, &soundID);
AudioServicesPlaySystemSound (soundID);

哪个有效,但只适用于短句(约不超过10个字) 我究竟做错了什么?如何在不降低语音质量的情况下解决这个问题或将其分成几个文本?

2 个答案:

答案 0 :(得分:3)

Google TTS仅限于 100个字符

所以你应该将你的长句分成小的100个字符块并将其传递给Google TTS方法。

您可以通过实施以下步骤来实现这一目标。

  1. 将你的长句分成小的100个字符块。
  2. 使用第一个拆分的100个字符串来调用Google TTS。
  3. 使用Google TTS& amp; AVAudioPlayer
  4. 实施AVAudioPlayer audioPlayerDidFinishPlaying委托。
  5. 在该代表中,使用第二个拆分的100个字符串来调用Google TTS。
  6. 递归调用该进程,直到到达最后一个字符。
  7. 以下是我为您创建的 Google-TTS-Library-For-iOS 库:)

答案 1 :(得分:2)

Google TTS限制为100个字符。

我最近创建了一个lib,它帮助解决了这个问题。 有一些改进,但请自由使用它。 GoogleTTSAPI

相关问题