如何在应用程序中使用iOS的内置文本到语音功能? [英] How do I use iOS's in-built text to speech function from within an app?
问题描述
我正在构建一个帮助学生学习外语的应用程序。我注意到当我在设置的辅助功能菜单中打开说出选择时,iPhone可以在Safari中读取外语文本。是否有可能以编程方式在手机上使用内置的文本转语音软件读取在UIView中显示的外来词(NSString)?
I'm in the process of building a app that helps students learn foreign languages. I notice the iPhone can read foreign language text in Safari when I have "Speak Selection" turned on in the Accessibility menu in settings. Is it possible to programmatically have the in-built text-to-speech software on the phone read a foreign word (an NSString) which is being displayed in a UIView?
推荐答案
我也尝试在我的应用程序中实现TTS,我试图用一些SDK实现它,但我不能。现在我正在使用 GOOGLE TRANSLATE API [ http://www.translate.google.com/translate_tts?tl=en&q=%@ ,text]。它将隐藏您的文字并为您提供运行音频文件所需的音频文件将它存储在Document目录中后[或根据需要自定义]。只需使用此代码。希望它有所帮助。
Me too tried to implement TTS in my application, i tried to implement it with some SDK but i cant. Now i am using GOOGLE TRANSLATE API ["http://www.translate.google.com/translate_tts?tl=en&q=%@",text"]. that will covert your text and give you a audio file you need to run the audio file after you stored it in Document directory [or customize as you like]. Just use this code. Hope it will help.
//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];
}
这篇关于如何在应用程序中使用iOS的内置文本到语音功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!