0

我正在构建一个帮助学生学习外语的应用程序。我注意到当我在设置的辅助功能菜单中打开“朗读选择”时,iPhone 可以在 Safari 中阅读外语文本。是否可以以编程方式让手机上的内置文本转语音软件读取 UIView 中显示的外来词(NSString)?

4

1 回答 1

2

我也尝试在我的应用程序中实现 TTS,我尝试使用一些 SDK 来实现它,但我做不到。现在我正在使用GOOGLE TRANSLATE API [" http://www.translate.google.com/translate_tts?tl=en&q=%@ ",text"]。它将隐藏您的文本并为您提供需要运行的音频文件将音频文件存储在 Document 目录[或根据需要自定义]。只需使用此代码。希望它会有所帮助。

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

    NSString *text = textToConvert.text;
    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];


    NSError        *err;
    if ([[NSFileManager defaultManager] fileExistsAtPath:path])
    {
//        player = [[AVAudioPlayer alloc] initWithContentsOfURL:
//                  [NSURL fileURLWithPath:path] error:&err];
////        player.volume = 0.4f;
//        [player prepareToPlay];
////        [player setNumberOfLoops:0];
//        [player play];


        player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&err];
//        player.delegate = self;

        [player prepareToPlay];
        [player play];
    }
于 2013-04-08T04:22:27.007 回答