如何在应用程序中使用iOS的内置文本到语音功能?

时间:2013-04-08 04:06:56

标签: ios objective-c text-to-speech

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

1 个答案:

答案 0 :(得分:2)

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

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