一.基本常识
TTS(Text To Speech),语音合成手艺,是指把原本的文本信息转换成能够发音的语音旌旗灯号,在GPS导航等需要人机交互斗劲多的场所经常会用到。 iPhone系统自己没有供给TTS引擎,可是可以使用外部数据的体例使iPhone具有TTS功能。
二.具体介绍
今朝找到两种可以在iPhone上免费使用TTS的体例,一种是使用Acapela为iPhone开发的工具包,另一种是使用Google Translate的TTS接口。
以下介绍Google Translate的TTS接口:
获取音频并保存起来:
NSString *urlString = [@"http://translate.google.com/translate_tts?tl=en&q=" stringByAppendingString:@"I+am+techcrunch"];
NSURL *url = [[NSURL alloc] initWithString:[urlString stringByReplacingOccurrencesOfString:@" " withString:@"+"]];
//获得返回的mp3文件,格式为NSdata
NSData *voiceData = [[NSData alloc] initWithContentsOfURL:url];
[NSThread sleepForTimeInterval:3.0];//等待3秒获取google词库的发音数据
if(voiceData)
{
NSLog(@"已经1次性获取到voice");
}
else
{
int k=0;
while(k<10&&!voiceData)//若voiceData为空,则继续获取voiceData5次,防止单词没有读音
{
NSString *urlString = [@"http://translate.google.com/translate_tts?tl=en&q=" stringByAppendingString:@"I+love+techcrunch "];
NSURL *url = [[NSURL alloc] initWithString:[urlString stringByReplacingOccurrencesOfString:@" " withString:@"+"]];
//获得返回的mp3文件,格式为NSdata
voiceData = [[NSData alloc] initWithContentsOfURL:url];
[NSThread sleepForTimeInterval:5.0];
k++;
}
if(voiceData){NSLog(@"第%d次获取到voice",k+1);}
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(@"%@",documentsDirectory);
[voiceData writeToFile:[documentsDirectory stringByAppendingPathComponent:@"test2"] atomically:YES];
[voiceData release];
读取音频并播放:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* appFile =[documentsDirectory stringByAppendingPathComponent:@"test2"];
NSURL* filePath = [NSURL fileURLWithPath:appFile isDirectory:NO];
_wordData = [NSData dataWithContentsOfURL:filePath];;
//保证静音模式下也能播放
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *error = nil;
BOOL b = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&error];
b = [audioSession setActive:YES error:&error];
//播放
_avAudioPlayer = [[AVAudioPlayer alloc] initWithData:_wordData error:nil];
_avAudioPlayer.delegate = self;
_avAudioPlayer.volume = 1.0f;
[_avAudioPlayer prepareToPlay];//分配播放所需的资源,并将其加入内部播放队列
[_avAudioPlayer play];